当使用Python的子进程模块和communication()方法时,我如何检索退出代码?

相关代码:

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

我应该换一种方法吗?


当前回答

这对我很管用。它还打印子进程返回的输出

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

其他回答

Exitcode = data.wait()。如果子进程写入标准输出/错误,和/或从标准输入读取,并且没有对等点,则子进程将被阻塞。

这对我很管用。它还打印子进程返回的输出

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

当它完成时,popen . communication将设置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。

.poll()将更新返回代码。

Try

child = sp.Popen(openRTSP + opts.split(), stdout=sp.PIPE)
returnCode = child.poll()

此外,在.poll()被调用之后,返回代码可以作为child.returncode在对象中使用。

在调用process. communication()之后使用process.wait()。 例如:

import subprocess

process = subprocess.Popen(['ipconfig', '/all'], stderr=subprocess.PIPE, stdout=subprocess.PIPE)
stdout, stderr = process.communicate()
exit_code = process.wait()
print(stdout, stderr, exit_code)