我正在编写一些使用multiprocessing
模块的代码。但是,由于我是新手,经常会出现一些错误,导致主应用程序停止运行。
但是,该应用程序的子级仍然保持运行,并且我在任务管理器列表中看到一长串正在运行的 pythonw
进程。
发生错误后,我该怎么做才能确保所有子进程也被杀死?
最佳答案
这个难题有两部分。
- 如何检测并终止所有子进程?
- 如何尽最大努力确保第 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/