我在后台运行一个漫长的过程(实际上是另一个python脚本)。 我需要知道什么时候,它已经完成。 我发现, Popen.poll()
总是一个后台进程返回0。 是否有另一种方式做到这一点?
p = subprocess.Popen("sleep 30 &", shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
a = p.poll()
print(a)
上面的代码永远不会打印None
。
我在后台运行一个漫长的过程(实际上是另一个python脚本)。 我需要知道什么时候,它已经完成。 我发现, Popen.poll()
总是一个后台进程返回0。 是否有另一种方式做到这一点?
p = subprocess.Popen("sleep 30 &", shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
a = p.poll()
print(a)
上面的代码永远不会打印None
。
你不需要使用shell backgrounding &
语法, 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
你不应该用在最后符号运行你的脚本。 由于外壳叉的过程,并且返回退出代码0。
我想你想要么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)
当然,这些持有主线程和等待其他进程完成,这可能是坏的。 如果你想忙等待,那么你可以简单地包裹在一个循环的原代码。 (你的原代码没有打印“无”对我来说,BTW)
在循环溶液中的包装的实施例:
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)