在Windows上优雅地终止子Python进程,最终子句运行

在Windows上,我有一些父进程启动subprocess的场景。 出于各种原因 – 父进程可能要中止subprocess,但是(这很重要) 允许它清理 – 即运行finally子句:

try: res = bookResource() doStuff(res) finally: cleanupResource(res) 

(这些东西可能会embedded到更近的环境中,而且一般都是围绕硬件locking/数据库状态)

问题是,我无法find一种方法来在Windows中发信号给孩子(就像我在Linux环境中那样),这样在终止之前就会运行清理。 我认为这需要使subprocess以某种方式引发exception(如Ctrl-C所示)。

我试过的东西:

  • os.kill
  • os.signal
  • ctypes.windll.kernel32.GenerateConsoleCtrlEvent(1, p.pid) creationFlags并使用ctypes.windll.kernel32.GenerateConsoleCtrlEvent(1, p.pid) abrt信号。 这需要一个信号陷阱和不雅的循环来阻止它立即中止。
  • ctypes.windll.kernel32.GenerateConsoleCtrlEvent(0, p.pid) – ctrl-c事件 – 什么都没做。

有没有人有这样做的一个绝对的方式,以便儿童进程可以清理?

我能够得到GenerateConsoleCtrlEvent像这样工作:

 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" 

产量

 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