【问题标题】:Run subprocess without kill when kill parent杀死父进程时运行子进程而不杀死
【发布时间】:2018-10-14 07:50:29
【问题描述】:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import subprocess

np_mpi = "1"
s_port = "11111"

cmd = "/data/ParaView/bin/mpiexec" + " -np " + \
    np_mpi + " /data/ParaView/bin/pvserver " + \
    "--server-port=" + \
    s_port + " -display " + " :0.0 " + \
    " --force-offscreen-rendering "

subprocess.call(cmd, shell=True)

我需要运行这个子进程,但我希望它在后台运行,并且在主进程死掉时不会杀死它。我该怎么做?终端没有回显怎么办?

目前这可行,但不继续使用脚本 python 的其余部分...

...更新... 我试试

subprocess.Popen(['nohup', cmd],
             stdout=open('/dev/null', 'w'),
             stderr=open('log.log', 'a'),
             preexec_fn=os.setpgrp
             ) 

但日志文件显示

nohup: failed to run command ‘/data/ParaView/bin/mpiexec -np 1 
/data/ParaView/bin/pvserver --server-port=11111 -display  :0.0  --force- 
offscreen-rendering ’: No such file or directory

和命令

 subprocess.call(cmd, shell=True)

为什么 nohup 会失败?

【问题讨论】:

  • 您在寻找nohup吗?
  • @abarnert 是的,我尝试使用 subprocess.Popen(['nohup', cmd], stdout=open('/dev/null', 'w'), stderr=open('log.log', 'a'), preexec_fn=os.setpgrp ) ....它适用于后台,但失败 "nohup: failed to run command '/data/ParaView/bin/mpiexec -np 1 / data/ParaView/bin/pvserver --server-port=11111 -display :0.0 --force-offscreen-rendering ': 没有这样的文件或目录”。当使用 subprocess.call 和 shell=True 运行时,该命令工作正常,但是使用 Popen 在日志文件中显示此错误。 @YaroslavSurzhikov
  • 你在这里混淆了不同的东西。如果要使用shell=True,则必须构建一个命令行字符串,包括开头的nohup 。如果您不想使用shell=True,则必须构建所有单独参数的列表。如果你在两者之间做一些事情,比如['nohup', cmd],你将整个cmd字符串作为一个巨大的参数传递,你希望nohup运行的程序的名称,当然没有这样的程序。/
  • @abarnert 谢谢,它在你的帮助下工作,非常感谢。

标签: python subprocess mpi child-process


【解决方案1】:

感谢@abarnert,修复:

 #!/usr/bin/env python3
 # -*- coding: utf-8 -*-

 import subprocess

 np_mpi = "1"
 mpiexec = "/data/ParaView/bin/mpiexec"
 pvserver = " /data/ParaView/bin/pvserver "
 s_port="--server-port=11111"

 cmd = ['nohup', mpiexec, "-np", np_mpi, pvserver,
       s_port, "-display", ":0.0", "--force-offscreen-rendering"
       ]

 subprocess.Popen(cmd,
                  stdout=open('/dev/null', 'w'),
                  stderr=open('log.log', 'a'),
                  preexec_fn=os.setpgrp
                  )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-08
    • 2011-09-09
    • 1970-01-01
    相关资源
    最近更新 更多