如何运行 Python 的子进程并将其留在后台 [英] How to run Python's subprocess and leave it in background

查看:79
本文介绍了如何运行 Python 的子进程并将其留在后台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have seen A LOT of posts regarding my topic, but actually I didn't find a solution for my problem. I'm trying to run a subprocess in a background, without wait for subprocess execution. The called subprocess is a shell script, which does a lot of different things. This is a small piece of my code:

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,在这里也没有帮助.

And my problem is that Python waits until subprocess.Popen finishes it's job. I read, that stdin(-out, -err)=None should solve this problem, but it's not. Also close_fds=True, doesn't help here.

推荐答案

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

From the Popen.communicate documentation (emphasis mine):

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

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:

If you don't want to wait for the process to terminate, then simply don't call communicate:

subprocess.Popen(full_command, close_fds=True)

这篇关于如何运行 Python 的子进程并将其留在后台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆