繁体   English   中英

如何在Windows上正常终止python进程

[英]How to gracefully terminate python process on windows

我在Windows 8.1的后台运行python 2.7进程。

有没有办法正常终止此过程并在关机或注销时执行清理?

尝试使用win32api.GenerateConsoleCtrlEvent。

我在这里为一个多处理python程序解决了这个问题: 优雅地终止Windows上的子Python进程,因此Final子句运行

我使用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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM