Answer the question
In order to leave comments, you need to log in
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
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
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 questionAsk a Question
731 491 924 answers to any question