【问题标题】:How to run Python's subprocess and leave it in background如何运行 Python 的子进程并将其留在后台
【发布时间】:2016-04-15 14:02:06
【问题描述】:

我看过很多关于我的主题的帖子,但实际上我没有找到解决问题的方法。 我正在尝试在后台运行子进程,而无需等待子进程执行。被调用的子进程是一个 shell 脚本,它做了很多不同的事情。 这是我的一小段代码:

print "Execute command:", full_command
subprocess.Popen(full_command, stdin=None, stdout=None, stderr=None, close_fds=True).communicate()
print "After subprocess"

我的问题是 Python 一直等到 subprocess.Popen 完成它的工作。我读到,stdin(-out, -err)=None 应该可以解决这个问题,但事实并非如此。还有 close_fds=True,在这里没有帮助。

【问题讨论】:

    标签: python subprocess popen


    【解决方案1】:

    来自Popen.communicate documentation(强调我的):

    与进程交互:将数据发送到标准输入。从标准输出读取数据并 stderr,直到到达文件结尾。 等待进程终止。 可选的输入参数应该是一个要发送给孩子的字符串 进程,或者 None,如果不应该向孩子发送数据。

    如果你不想等待进程终止,那么就不要调用communicate

    subprocess.Popen(full_command, close_fds=True)
    

    【讨论】:

    • 哦,这太容易让人看不出来了... ;) 感谢您的快速回答!
    • @mchfrnc 我不得不承认该方法的名称并没有使副作用非常清楚! ; )
    【解决方案2】:

    可能是另一种方法,具有检查子进程输出一段时间的可选功能,来自 github.com/hologram-io/hologram-python pppd.py 文件:

        self.proc = Popen(self._commands, stdout=PIPE, stderr=STDOUT)
    
        # set stdout to non-blocking
        fd = self.proc.stdout.fileno()
        fl = fcntl.fcntl(fd, fcntl.F_GETFL)
        fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
    

    【讨论】:

      猜你喜欢
      • 2015-11-20
      • 1970-01-01
      • 2013-12-16
      • 2011-08-12
      • 2016-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多