如何 运行 Python 的子进程并将其留在后台

How to run Python's subprocess and leave it in background

我已经看到很多关于我的主题的帖子,但实际上我没有找到解决我的问题的方法。 我试图在后台 运行 一个子进程,而不等待子进程执行。被调用的子进程是一个 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,在这里没有帮助。

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

Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child.

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

subprocess.Popen(full_command, close_fds=True)

可能是另一种方法,具有检查子进程输出一段时间的可选功能,来自 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)