1

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?

jossgray
  • 497
  • 6
  • 20
  • 1
    Set up an IPC communication channel and request that the Python program terminates via that channel – David Heffernan Jul 08 '15 at 14:57
  • 2
    might be somewhat related? http://stackoverflow.com/questions/1216788/win32-api-analog-of-sending-catching-sigterm – NightShadeQueen Jul 08 '15 at 14:58
  • Your issue sounds slightly different than mine, although they seem to be in the same ballpark. https://stackoverflow.com/questions/45199817/stopping-a-python-process-so-that-context-managers-still-call-exit-in-windo – Batman0730 Jul 19 '17 at 20:29

1 Answers1

2

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"
Batman0730
  • 487
  • 2
  • 5
  • 21