使用Python的subprocess
模块和communicate()
方法时如何检索退出代码?
相关代码:
import subprocess as sp
data = sp.Popen(openRTSP + opts.split(), stdout=sp.PIPE).communicate()[0]
我应该这样做吗?
Popen.communicate
将在完成时设置returncode
属性(*)。这是相关的文档部分:
Popen.returncode
The child return code, set by poll() and wait() (and indirectly by communicate()).
A None value indicates that the process hasn’t terminated yet.
A negative value -N indicates that the child was terminated by signal N (Unix only).
所以你可以这样做(我没有测试它,但它应该工作):
import subprocess as sp
child = sp.Popen(openRTSP + opts.split(), stdout=sp.PIPE)
streamdata = child.communicate()[0]
rc = child.returncode
(*)这是因为它的实现方式:在设置线程以读取子流后,它只调用wait
。
您应首先确保该进程已完成运行,并且已使用.wait
方法读取了返回代码。这将返回代码。如果您想稍后访问它,它将被存储为.returncode
对象中的Popen
。
exitcode = data.wait()
。子进程将被阻止如果它写入标准输出/错误,和/或从标准输入读取,并且没有对等。
.poll()
将更新返回代码。
尝试
child = sp.Popen(openRTSP + opts.split(), stdout=sp.PIPE)
returnCode = child.poll()
此外,在调用.poll()
之后,返回代码在对象中可用为child.returncode
。
这对我有用。它还会打印子进程返回的输出
child = subprocess.Popen(serial_script_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
retValRunJobsSerialScript = 0
for line in child.stdout.readlines()
child.wait()
print line
retValRunJobsSerialScript= child.returncode