How to execute code just before terminating the process in python?

╄→гoц情女王★ 提交于 2021-01-28 08:14:49

问题


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:

def worker(): while True: print('work') time.sleep(2) return

I run it by:

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()


回答1:


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.



来源:https://stackoverflow.com/questions/42560706/how-to-execute-code-just-before-terminating-the-process-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!