B
B
belmih2016-02-07 12:28:49
Python
belmih, 2016-02-07 12:28:49

How to properly organize the management of a running python script?

I need to implement a small application with its own CLI that accepts commands: start - start the server, stop - stop the server, statistics - display statistics.
I want to achieve a result like:

$ myserver.py start
$ myserver.py statistic
$ myserver.py stop

but I don't know how. I tried to do it through daemon A simple unix/linux daemon in Python , but it was not possible to collect statistics. Maybe I need to look towards subprocess ?
Tell me how to organize the management?
So far my solution looks like this:
class MyReceiver(object):

    def __init__(self):
        self.run = False
        
    def start(self):
        if self.run:
            print "The server is already running"
            return
        self.thread = threading.Thread(target=worker)
        self.thread.daemon = True
        self.thread.start()
        self.run = True

    def stop(self):
        if self.run:
            self.thread.join()
            self.run = False

    def get_statistic(self):
        return "statistic here"

def main():
    print "Hello! Use: start|stop|restart|statistic|exit"
    reciver = MyReceiver()
    reciver.start()
    try:
        while True:
            command = str(raw_input('myserver:'))
            if 'start' == command:
                reciver.start()
            elif 'stop' == command:
                reciver.stop()
                reciver.get_statistic()
            elif 'restart' == command:
                reciver.stop()
                time.sleep(.5)
                reciver.start()
            elif 'statistic' == command:
                reciver.get_statistic()
            elif 'exit' == command:
                reciver.stop()
                sys.exit(0)
            else:
                print "Unknown command"
            time.sleep(.2)
    except KeyboardInterrupt:
        reciver.stop()
        sys.exit(1)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sly_tom_cat ., 2016-02-07
@Sly_tom_cat

Why raw_input?
There is also sys.argv and a more advanced argparse library.
You can simply

if len(sys.argv) = 2:
  if sys.argv[1] = 'start':
    ....
  elif sys.argv[1] = 'stop':
    ....
  else:
    print('неизвестная команда')
else:
  print('неверное количество аргументв')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question