如何在python中终止进程之前执行代码? [英] How to execute code just before terminating the process in python?
问题描述
这个问题涉及 python 中的多处理.我想在终止进程时执行一些代码,更具体地说,在它即将终止之前.我正在寻找一种可以作为 python 程序的 atexit.register
的解决方案.
This question concerns multiprocessing in python. I want to execute some code when I terminate the process, to be more specific just before it will be terminated. I'm looking for a solution which works as atexit.register
for the python program.
我有一个看起来像的方法工作者:
I have a method worker which looks:
定义工人():为真:打印('工作')时间.sleep(2)返回
def worker(): while True: print('work') time.sleep(2) return
我运行它:
proc = multiprocessing.Process(target=worker, args=())proc.start()
proc = multiprocessing.Process(target=worker, args=()) proc.start()
我的目标是在终止之前执行一些额外的代码,我这样做:
My goal is to execute some extra code just before terminating it, which I do by:
proc.terminate()
proc.terminate()
推荐答案
使用信号处理和拦截 SIGTERM:
Use signal handling and intercept SIGTERM:
import multiprocessing
import time
import sys
from signal import signal, SIGTERM
def before_exit(*args):
print('Hello')
sys.exit(0) # don't forget to exit!
def worker():
signal(SIGTERM, before_exit)
time.sleep(10)
proc = multiprocessing.Process(target=worker, args=())
proc.start()
time.sleep(3)
proc.terminate()
在子进程终止前产生所需的输出.
Produces the desirable output just before subprocess termination.
这篇关于如何在python中终止进程之前执行代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!