【发布时间】:2014-05-17 23:03:24
【问题描述】:
我正在编写一些使用multiprocessing 模块的代码。但是,由于我是新手,经常发生的情况是弹出一些错误,导致主应用程序停止。
但是,该应用程序的子进程仍在运行,我的任务管理器列表中有很长很长的正在运行的 pythonw 进程列表。
发生错误后,如何确保所有子进程也被杀死?
【问题讨论】:
标签: python-2.7 multiprocessing
我正在编写一些使用multiprocessing 模块的代码。但是,由于我是新手,经常发生的情况是弹出一些错误,导致主应用程序停止。
但是,该应用程序的子进程仍在运行,我的任务管理器列表中有很长很长的正在运行的 pythonw 进程列表。
发生错误后,如何确保所有子进程也被杀死?
【问题讨论】:
标签: python-2.7 multiprocessing
这个难题有两个部分。
对于第 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
【讨论】:
for p in ... p.terminate()?