python-2.7 - Python多处理: how to exit cleanly after an error?

标签 python-2.7 multiprocessing

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

但是,该应用程序的子级仍然保持运行,并且我在任务管理器列表中看到一长串正在运行的 pythonw 进程。

发生错误后,我该怎么做才能确保所有子进程也被杀死?

最佳答案

这个难题有两部分。

  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

关于python-2.7 - Python多处理: how to exit cleanly after an error?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23716951/

相关文章:

java - 如何充分利用多处理器?

python - Python 中出现 IO 错误

android - 无法摆脱错误 "/usr/bin/ld: cannot find -lncurses"

python - Ubuntu 12.04 LTS : Update python 2. 7.3 到 2.7.6 不破坏依赖关系

assembly - 在不同处理器(x86程序集)上运行代码

python - 使用 python 更改线程中的对象值

Python 多处理锁机制在获取锁时失败

python - IO 任务中的 Python 多线程没有任何好处?

android - 在 Android 设备中使用 sklearn

python - 将字典存储在文件中供以后检索