Skip to content Skip to sidebar Skip to footer

How To Execute Code Just Before Terminating The Process In Python?

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 1:

Use signal handling and intercept SIGTERM:

import multiprocessing
import time
import sys
from signal import signal, SIGTERM

defbefore_exit(*args):
    print('Hello')
    sys.exit(0)  # don't forget to exit!defworker():
    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.

Post a Comment for "How To Execute Code Just Before Terminating The Process In Python?"