2017-04-07 187 views
8

我用Python中的subprocess.Popen启动了一些子进程。 我想检查一个这样的过程是否完成。我发现了两种检查子进程状态的方法,但都似乎迫使进程完成。 一个使用process.communicate()并打印返回码,如解释here。 另一种方法是简单地调用process.wait()并检查它是否返回0.有没有办法检查子进程是否仍在运行?

有没有一种方法可以检查进程是否仍在运行,而无需等待进程完成?

+0

['Popen.poll()'](https://docs.python.org/2/library/subprocess.html#subprocess.Popen.poll)? – asongtoruin

+0

@ason​​gtoruin打印无,即使过程完成。 – ahura

+0

过程完成后应停止打印'无'。你如何调用你的子进程? – asongtoruin

回答

8

Ouestion: ... a way to check if a process is still running ...

例如你可以做到这一点:

p = subprocess.Popen(... 
""" 
A None value indicates that the process hasn't terminated yet. 
""" 
poll = p.poll() 
if poll == None: 
    # p.subprocess is alive 

Python » 3.6.1 Documentation popen-objects

测试使用Python 3.4.2

+0

这给出了“AttributeError:'Popen'对象没有属性'进程'” – ahura

+1

我可以做p.poll ()。即使完成该过程,它也会返回None。我知道这是因为我调用的脚本产生了一个输出文件,它仍然会返回None。 另外,我可以打印给出0的p.wait(),但打印后面的p.poll()仍然给出None。 – ahura

+2

语义,但我相信'如果轮询是无'是写它的首选方式。 – asongtoruin

0

您可以使用subprocess.check_output来查看您的输出。

试试这个代码:

import subprocess 
subprocess.check_output(['your command here'], shell=True, stderr=subprocess.STDOUT) 

希望这有助于!

0

做好

myProcessIsRunning = poll() is None 

正如主要答案中所建议的那样,是推荐的方法和最简单的方法来检查一个进程是否正在运行。 (并且它也以jython的方式工作)

如果您没有手动检查它的流程实例。 然后使用操作系统TaskList/Ps进程。

在Windows上,我的命令如下所示:

filterByPid = "PID eq %s" % pid 
     pidStr = str(pid) 
     commandArguments = ['cmd', '/c', "tasklist", "/FI", filterByPid, "|", "findstr", pidStr ] 

这实质上是在做同样的事情,以下命令行:

cmd /c "tasklist /FI "PID eq 55588" | findstr 55588" 

在Linux上,我做同样的使用:

pidStr = str(pid) 
commandArguments = ['ps', '-p', pidStr ] 

ps命令将已经返回了错误代码0/1,具体取决于Ò n是否找到过程。在Windows上,您需要find字符串命令。

这是该followig堆栈溢出线程上讨论相同的方法:

Verify if a process is running using its PID in JAVA

注: 如果使用这种方法,remeber来包装你的命令调用在
尝试: foundRunningProcess =子进程。check_output(argumentsArray,** kwargs) 返回true 除了异常的错误: 返回False

请注意,如果您正在使用VS代码开发和使用纯Python和Jython小心。 在我的环境中,我担心poll()方法不起作用,因为我怀疑这个过程肯定已经结束了,确实正在运行。 这个过程已经推出了Wild。。在我要求野蝇停止后,壳仍在等待用户“按任意键继续......”。

为了玩完这个过程中,在纯Python下面的代码是工作:

process.stdin.write(os.linesep) 

在Jython中,我必须解决这个问题的代码如下所示:

print >>process.stdin, os.linesep 

而且有了这种差异,这个过程确实完成了。 jython.poll()开始告诉我这个过程确实完成了。

相关问题