一尘不染

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

python

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

相关代码:

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

我应该以其他方式这样做吗?


阅读 178

收藏
2021-01-20

共1个答案

一尘不染

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

2021-01-20