Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
正确退出systemctl停止服务上的python脚本_Python_Exception_Try Catch_Exit - Fatal编程技术网

正确退出systemctl停止服务上的python脚本

正确退出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运行并且我调用

我的脚本在按下CTLC+C时通过
退出,键盘中断除外,如下所示:

....

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,并且在任何给定的时间终止都不会对它们造成任何后果,那么您可以让它们死掉。否则,您应该显式地编写逻辑代码,以便在接收到信号时正确关闭它们