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

问题描述 投票:158回答:5

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

相关代码:

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

我应该这样做吗?

python subprocess
5个回答
231
投票

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


8
投票

您应首先确保该进程已完成运行,并且已使用.wait方法读取了返回代码。这将返回代码。如果您想稍后访问它,它将被存储为.returncode对象中的Popen


6
投票

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


2
投票

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

尝试

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

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


1
投票

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

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
© www.soinside.com 2019 - 2024. All rights reserved.