【问题标题】:How to attach a value to the multiprocessing.current_process() in python?如何将值附加到 python 中的 multiprocessing.current_process()?
【发布时间】: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


【解决方案1】:

为清楚起见,我们使用以下术语:“父进程”是您启动的初始 Python 进程; “子进程”是您通过multiprocessing 模块启动的进程; “孙进程”是您通过subprocess.Popen 启动的进程。

问题是您的f 在子进程中执行,但是当您调用ProcessWrapper 实例的terminate 方法时,您正在父进程中运行代码,其中subprocess 属性是从未分配给multiprocessing.current_process() 返回的对象。

要做你想做的事,你可以使用process groups 让父进程直接终止孙进程,或者(作为更细粒度的手动方法)从父进程向子进程发送信号并获得信号子进程中的处理程序终止孙子进程。

【讨论】:

  • 您能告诉我如何将处理程序附加到子进程以终止孙子进程吗?
猜你喜欢
  • 2014-06-07
  • 1970-01-01
  • 2011-03-24
  • 2021-12-21
  • 1970-01-01
  • 2016-12-30
  • 2013-12-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多