我在Windows 8.1的后台运行了一个python 2.7进程。
有没有办法优雅地终止此过程并在关机或注销时执行清理?
答案 0 :(得分:2)
尝试使用win32api.GenerateConsoleCtrlEvent。
我在这里为多处理python程序解决了这个问题: Gracefully Terminate Child Python Process On Windows so Finally clauses run
我使用subprocess.Popen测试了这个解决方案,它也可以工作。
这是一个代码示例:
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"