使用Python子进程通信方法时如何获取退出代码?

问题:

使用Python的subprocess模块和communicate()方法时,如何检索退出代码?
相关代码:

import subprocess as sp
data = sp.Popen(openRTSP + opts.split(), stdout=sp.PIPE).communicate()[0]

我应该这样做吗

回答:

 当Popen.communicate完成后,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

 
 
Code问答: http://codewenda.com/topics/python/
Stackoverflow: How to get exit code when using Python subprocess communicate method?

*转载请注明本文链接以及stackoverflow的英文链接

发表评论

电子邮件地址不会被公开。 必填项已用*标注

− 2 = 6