【问题标题】:Python multiprocessing: how to exit cleanly after an error?Python多处理:错误后如何干净地退出?
【发布时间】:2014-05-17 23:03:24
【问题描述】:

我正在编写一些使用multiprocessing 模块的代码。但是,由于我是新手,经常发生的情况是弹出一些错误,导致主应用程序停止。

但是,该应用程序的子进程仍在运行,我的任务管理器列表中有很长很长的正在运行的 pythonw 进程列表。

发生错误后,如何确保所有子进程也被杀死?

【问题讨论】:

    标签: python-2.7 multiprocessing


    【解决方案1】:

    这个难题有两个部分。

    1. 如何检测并杀死所有子进程?
    2. 如何尽最大努力确保第 1 部分中的代码在一个进程终止时运行?

    对于第 1 部分,您可以使用 multiprocessing.active_children() 获取所有活跃子节点的列表并使用 Process.terminate() 杀死它们。注意Process.terminate() 的使用带有通常的警告。

    from multiprocessing import Process
    import multiprocessing
    
    def f(name):
        print 'hello', name
        while True: pass
    
    if __name__ == '__main__':
        for i in xrange(5):
            p = Process(target=f, args=('bob',))
            p.start()
    
        # At user input, terminate all processes.
        raw_input("Press Enter to terminate: ")
        for p in multiprocessing.active_children():
           p.terminate()
    

    第 2 部分的一个解决方案是使用sys.excepthook,如this answer 中所述。这是一个组合示例。

    from multiprocessing import Process
    import multiprocessing
    import sys
    from  time import sleep
    
    def f(name):
        print 'hello', name
        while True: pass
    
    def myexcepthook(exctype, value, traceback):
        for p in multiprocessing.active_children():
           p.terminate()
    
    if __name__ == '__main__':
        for i in xrange(5):
            p = Process(target=f, args=('bob',))
            p.start()
        sys.excepthook = myexcepthook
    
        # Sleep for a bit and then force an exception by doing something stupid.
        sleep(1)
        1 / 0
    

    【讨论】:

    • 我想,作为扩展,我可以有一个 try/except 块。如果捕获到异常,那么我可以在打印捕获到的错误之前运行for p in ... p.terminate()
    • @user89,是的,可以。我刚刚更新以展示如何为 uncaught 异常更新全局异常处理程序。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-01
    • 1970-01-01
    • 2021-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多