【问题标题】:Have subprocess.Popen only wait on its child process to return, but not any grandchildren让 subprocess.Popen 只等待其子进程返回,而不是任何孙子进程
【发布时间】:2021-03-29 01:22:42
【问题描述】:

我有一个执行此操作的 python 脚本:

p = subprocess.Popen(pythonscript.py, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=False) 
theStdin=request.input.encode('utf-8')
(outputhere,errorshere) = p.communicate(input=theStdin)

它按预期工作,它通过 p.communicate() 等待子进程完成。但是在 pythonscript.py 中,我想“解雇并忘记”一个“孙子”进程。我目前正在通过覆盖 join 函数来做到这一点:

class EverLastingProcess(Process):
    def join(self, *args, **kwargs):
        pass # Overwrites join so that it doesn't block. Otherwise parent waits.
    def __del__(self):
        pass

然后像这样开始:

p = EverLastingProcess(target=nameOfMyFunction, args=(arg1, etc,), daemon=False)
p.start()

这也很好,我只是在 bash 终端或 bash 脚本中运行 pythonscript.py。当 EverLastingProcess 启动的子进程继续运行时,控制和响应返回。但是,当我运行 pythonscript.py 和 Popen 运行如上所示的进程时,从时间来看,Popen 正在等待孙子完成。 我怎样才能使 Popen 只等待子进程,而不是任何孙子进程?

【问题讨论】:

  • 不会将 daemon=True 传递给 EverLastingProcess 帮助吗?
  • @rasjani 我使用 daemon=False 因为我希望子进程在父进程完成时不会死亡。它应该继续独立做自己的事情。

标签: python subprocess popen


【解决方案1】:

一位同事的工作答案,更改为 shell=True 如下:

p = subprocess.Popen(pythonscript.py, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)

我已经测试过,孙子进程在子进程返回后仍然保持活动状态,而无需等待它们完成。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-01
    • 2021-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-27
    相关资源
    最近更新 更多