【发布时间】:2014-01-27 00:32:27
【问题描述】:
我有一个 python multiprocessing 进程,它产生子进程来运行各种命令。我想将进程包装在另一个类中,如果父进程终止,则该类首先终止子进程。
这是我目前所拥有的:
def f():
current_process = multiprocessing.current_process()
current_process.subprocess = subprocess.Popen(...) # execute command taking a lot of time to run.
class ProcessWrapper(Process):
def __init__(self, function):
super(ProcessWrapper, self).__init__(target=function)
def terminate(self):
if hasattr(self, 'subprocess'):
self.subprocess.terminate() # never gets here
super(ProcessWrapper, self).terminate()
def main():
p = ProcessWrapper(f)
p.start()
time.sleep(5)
p.terminate()
问题似乎是子进程从未附加到父进程。这是什么原因?实现这一目标的最佳方法是什么?
【问题讨论】:
-
hasattr是一个内置函数,而不是一个方法。执行terminate时,您的代码将引发AttributeError。 -
您的编辑仍然无效。你想要
hasattr(self, 'subprocess')。 -
已修复。试图发布我的代码的简短示例是一个不幸。
标签: python subprocess multiprocessing