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

时间:2011-04-12 07:11:03

标签: python subprocess

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

相关代码:

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

我应该采取另一种方式吗?

7 个答案:

答案 0 :(得分:228)

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

答案 1 :(得分:8)

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

答案 2 :(得分:6)

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

答案 3 :(得分:1)

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

尝试

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

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

答案 4 :(得分: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

答案 5 :(得分:0)

致电process.wait()后使用process.communicate()
例如:

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)

答案 6 :(得分:0)

请查看评论。

代码:

import subprocess


class MyLibrary(object):

    def execute(self, cmd):
        return subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True,)
      
    def list(self):
        command = ["ping", "google.com"]
        sp = self.execute(command)
        status = sp.wait()  # will wait for sp to finish
        out, err = sp.communicate()
        print(out)
        return status # 0 is success else error


test = MyLibrary()

print(test.list())

输出:

C:\Users\shita\Documents\Tech\Python>python t5.py

Pinging google.com [142.250.64.78] with 32 bytes of data:
Reply from 142.250.64.78: bytes=32 time=108ms TTL=116
Reply from 142.250.64.78: bytes=32 time=224ms TTL=116
Reply from 142.250.64.78: bytes=32 time=84ms TTL=116
Reply from 142.250.64.78: bytes=32 time=139ms TTL=116

Ping statistics for 142.250.64.78:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 84ms, Maximum = 224ms, Average = 138ms

0