在 Python 3 中使用 SIGTERM 时允许进程完成而不是被中断
Allow process to finish rather than be interrupted when SIGTERM is used in Python 3
我正在开发一些代码,当从 unix 命令行发送 sigterm 信号时,我需要正常关闭这些代码。我发现这个示例 效果很好,但它有一个问题。
代码:
import signal
import time
class GracefulKiller:
def __init__(self):
signal.signal(signal.SIGTERM, self.exit_gracefully)
self.kill_now = False
def exit_gracefully(self, signum, frame):
self.kill_now = True
def run_something(self):
print("starting")
time.sleep(5)
print("ending")
if __name__ == '__main__':
killer = GracefulKiller()
print(os.getpid())
while True:
killer.run_something()
if killer.kill_now:
break
print("End of the program. I was killed gracefully :)")
当您传递 kill 命令 kill -15 <pid>
时,run_something 方法被中断并且进程被优雅地杀死。 但是,有没有办法做到这一点,以便 run_something 方法可以在进程被终止之前完成? 即防止打扰?
期望的输出:
>>> starting
*kill executed during the middle sleep*
>>> ending
>>> End of the program. I was killed gracefully :)
我的用例是这将变成一个下载脚本,如果我想终止进程,我希望进程在终止之前完成下载...
thread.join()
即使捕获到退出信号,也会等待线程完成。
import threading
import Queue
import time
def download_for(seconds=5):
for i in range(seconds):
print("downloading...")
time.sleep(1)
print("finished download")
download_thread = threading.Thread(target=download_for, args=(3,))
download_thread.start()
# this waits till the thread finishes even if an exit signal was received
download_thread.join()
# this would just stop the download midway
# download_for(seconds=5)
答案在原题中。我只是把它留在这里供以后的 Google 搜索者使用。
我从来没有遇到过问题,我的终端只是在执行 kill
命令后打印 'ending' 时遇到问题。
我正在开发一些代码,当从 unix 命令行发送 sigterm 信号时,我需要正常关闭这些代码。我发现这个示例 效果很好,但它有一个问题。
代码:
import signal
import time
class GracefulKiller:
def __init__(self):
signal.signal(signal.SIGTERM, self.exit_gracefully)
self.kill_now = False
def exit_gracefully(self, signum, frame):
self.kill_now = True
def run_something(self):
print("starting")
time.sleep(5)
print("ending")
if __name__ == '__main__':
killer = GracefulKiller()
print(os.getpid())
while True:
killer.run_something()
if killer.kill_now:
break
print("End of the program. I was killed gracefully :)")
当您传递 kill 命令 kill -15 <pid>
时,run_something 方法被中断并且进程被优雅地杀死。 但是,有没有办法做到这一点,以便 run_something 方法可以在进程被终止之前完成? 即防止打扰?
期望的输出:
>>> starting
*kill executed during the middle sleep*
>>> ending
>>> End of the program. I was killed gracefully :)
我的用例是这将变成一个下载脚本,如果我想终止进程,我希望进程在终止之前完成下载...
thread.join()
即使捕获到退出信号,也会等待线程完成。
import threading
import Queue
import time
def download_for(seconds=5):
for i in range(seconds):
print("downloading...")
time.sleep(1)
print("finished download")
download_thread = threading.Thread(target=download_for, args=(3,))
download_thread.start()
# this waits till the thread finishes even if an exit signal was received
download_thread.join()
# this would just stop the download midway
# download_for(seconds=5)
答案在原题中。我只是把它留在这里供以后的 Google 搜索者使用。
我从来没有遇到过问题,我的终端只是在执行 kill
命令后打印 'ending' 时遇到问题。