Skip to main content
 首页 » 编程设计

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

2025年05月04日13落叶

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