How To Gracefully Terminate Python Process On Windows
I have a python 2.7 process running in the background on Windows 8.1. Is there a way to gracefully terminate this process and perform cleanup on shutdown or log off?
Solution 1:
Try using win32api.GenerateConsoleCtrlEvent.
I solved this for a multiprocessing python program here: Gracefully Terminate Child Python Process On Windows so Finally clauses run
I tested this solution using subprocess.Popen, and it also works.
Here is a code example:
import time
import win32api
import win32con
from multiprocessing import Process
def foo():
try:
while True:
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"
Post a Comment for "How To Gracefully Terminate Python Process On Windows"