Cod*_*ger 16 python subprocess popen python-3.x
我在后台运行一个很长的进程(实际上是另一个python脚本).我需要知道它什么时候结束.我发现Popen.poll()总是为后台进程返回0.还有另一种方法吗?
p = subprocess.Popen("sleep 30 &", shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
a = p.poll()
print(a)
Run Code Online (Sandbox Code Playgroud)
上面的代码从不打印None.
dbr*_*dbr 36
您不需要使用shell后台&语法,因为subprocess它将在后台单独运行该过程
只需正常运行命令,然后等待直到Popen.poll返回not None
import time
import subprocess
p = subprocess.Popen("sleep 30", shell=True)
# Better: p = subprocess.Popen(["sleep", "30"])
# Wait until process terminates
while p.poll() is None:
time.sleep(0.5)
# It's done
print "Process ended, ret code:", p.returncode
Run Code Online (Sandbox Code Playgroud)
bla*_*ora 11
我想你想要popen.wait()或者popen.communicate()命令.通信将抓住stdout与stderr您已投入数据PIPE.如果另一个项目是Python脚本,我会shell=True通过执行以下操作来避免运行调用:
p = subprocess.Popen([python.call, "my", params, (go, here)], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = p.communicate()
print(stdout)
print(stderr)
Run Code Online (Sandbox Code Playgroud)
当然这些包含主线程并等待其他进程完成,这可能是坏事.如果您想忙等待,那么您可以简单地将原始代码包装在一个循环中.(您的原始代码确实为我打印"无",顺便说一句)
循环解决方案中的包装示例:
p = subprocess.Popen([python.call, "my", params, (go, here)], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
while p.poll() == None:
# We can do other things here while we wait
time.sleep(.5)
p.poll()
(results, errors) = p.communicate()
if errors == '':
return results
else:
raise My_Exception(errors)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
46095 次 |
| 最近记录: |