我正在编写一些使用的代码multiprocessing
模块。然而,由于我是新手,经常发生的情况是弹出一些错误,导致主应用程序停止运行。
但是,该应用程序的子级仍然保持运行,并且我得到一长串正在运行的列表pythonw
我的任务管理器列表中的进程。
发生错误后,我该怎么做才能确保所有子进程也被杀死?
这个难题有两部分。
- 如何检测并杀死所有子进程?
- 我怎样才能尽最大努力确保在一个进程终止时运行第 1 部分中的代码?
对于第 1 部分,您可以使用multiprocessing.active_children() https://docs.python.org/2/library/multiprocessing.html#miscellaneous获取所有活跃孩子的列表并杀死他们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
,如中所述这个答案 https://stackoverflow.com/a/6598286/391161。这是一个组合示例。
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)