Skip to content Skip to sidebar Skip to footer

Gracefully Terminate Child Python Process On Windows So Finally Clauses Run

On Windows boxes, I have a number of scenarios where a parent process will start a child process. For various reasons - the parent process may want to abort the child process but (

Solution 1:

I was able to get the GenerateConsoleCtrlEvent working like this:

import time
import win32api
import win32con
from multiprocessing import Process


deffoo():
    try:
        whileTrue:
            print("Child process still working...")
            time.sleep(1)
    except KeyboardInterrupt:
        print"Child process: caught ctrl-c"if __name__ == "__main__":
    p = Process(target=foo)
    p.start()
    time.sleep(2)

    print"sending ctrl c..."try:
        win32api.GenerateConsoleCtrlEvent(win32con.CTRL_C_EVENT, 0)
        while p.is_alive():
            print("Child process is still alive.")
            time.sleep(1)
    except KeyboardInterrupt:
        print"Main process: caught ctrl-c"

Output

Child process still working...
Child process still working...
sending ctrl c...
Child process is still alive.
Child process: caught ctrl-c
Main process: caught ctrl-c

Post a Comment for "Gracefully Terminate Child Python Process On Windows So Finally Clauses Run"