正确退出systemctl停止服务上的python脚本
我的脚本在按下CTLC+C时通过正确退出systemctl停止服务上的python脚本,python,exception,try-catch,exit,Python,Exception,Try Catch,Exit,我的脚本在按下CTLC+C时通过退出,键盘中断除外,如下所示: .... try: thread1.start() thread2.start() while True: time.sleep(1) except (KeyboardInterrupt, SystemExit, Exception): print("exiting") # handle proper threads exit 但是,当脚本作为systemd运行并且我调用
退出,键盘中断除外,如下所示:
....
try:
thread1.start()
thread2.start()
while True:
time.sleep(1)
except (KeyboardInterrupt, SystemExit, Exception):
print("exiting")
# handle proper threads exit
但是,当脚本作为systemd运行并且我调用systemctl stop myscript.service
时,“exiting”消息不会记录到syslogger中,因此我知道除了之外的不会执行。系统退出
和异常
似乎没有在服务停止时发出。systemctl发布了什么,以便我可以在脚本的try-except
部分捕获它
另外,在调用systemctl stop
时,我是否需要注意正确的线程退出,否则它将很好地处理我的脚本?您可以在systemd config文件中指定选项,指定发送给进程的退出信号。然后,您可以修改python脚本,使用模块捕获指定的信号,并相应地执行退出代码
至于其他线程,这取决于它们的关键程度和实例化方式。如果它们被实例化为daemonic,并且在任何给定的时间终止都不会对它们造成任何后果,那么您可以让它们死掉。否则,您应该显式地编写逻辑代码,以便在接收到信号时正确关闭它们