很好地终止后台 python 脚本
Terminate background python script nicely
我正在 运行 使用命令 python script.py &
在后台创建一个 python 脚本。该脚本可能如下所示。
import time
def loop():
while True:
time.sleep(1)
if __name__=='__main__':
try:
loop()
except KeyboardInterrupt:
print("Terminated properly")
当谈到终止脚本时,我想在它停止之前做一些清理工作(例如打印 "Terminated properly")。如果我 运行 作为当前进程,这将在键盘中断后由 except
语句处理。
使用kill PID
命令意味着永远不会执行清理。如何停止后台进程并在它终止之前执行一些代码行?
使用finally
子句:
def loop():
while True:
time.sleep(1)
if __name__=='__main__':
try:
loop()
except KeyboardInterrupt:
print("Terminated properly")
finally:
print('executes always')
您可以使用信号模块来捕获通过 kill 发送到您的脚本的任何信号。
您设置了一个信号处理程序来捕获将执行清理的相关信号。
import signal
import time
running = 0
def loop ():
global running
running = 1
while running:
try: time.sleep(0.25)
except KeyboardInterrupt: break
print "Ended nicely!"
def cleanup (signumber, stackframe):
global running
running = 0
signal.signal(signal.SIGABRT, cleanup)
signal.signal(signal.SIGTERM, cleanup)
signal.signal(signal.SIGQUIT, cleanup)
loop()
我正在 运行 使用命令 python script.py &
在后台创建一个 python 脚本。该脚本可能如下所示。
import time
def loop():
while True:
time.sleep(1)
if __name__=='__main__':
try:
loop()
except KeyboardInterrupt:
print("Terminated properly")
当谈到终止脚本时,我想在它停止之前做一些清理工作(例如打印 "Terminated properly")。如果我 运行 作为当前进程,这将在键盘中断后由 except
语句处理。
使用kill PID
命令意味着永远不会执行清理。如何停止后台进程并在它终止之前执行一些代码行?
使用finally
子句:
def loop():
while True:
time.sleep(1)
if __name__=='__main__':
try:
loop()
except KeyboardInterrupt:
print("Terminated properly")
finally:
print('executes always')
您可以使用信号模块来捕获通过 kill 发送到您的脚本的任何信号。 您设置了一个信号处理程序来捕获将执行清理的相关信号。
import signal
import time
running = 0
def loop ():
global running
running = 1
while running:
try: time.sleep(0.25)
except KeyboardInterrupt: break
print "Ended nicely!"
def cleanup (signumber, stackframe):
global running
running = 0
signal.signal(signal.SIGABRT, cleanup)
signal.signal(signal.SIGTERM, cleanup)
signal.signal(signal.SIGQUIT, cleanup)
loop()