使用Python子进程通信方法时如何获取退出代码? [英] How to get exit code when using Python subprocess communicate method?

查看:85
本文介绍了使用Python子进程通信方法时如何获取退出代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I retrieve the exit code when using Python's subprocess module and the communicate() method?

相关代码:

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

我应该以另一种方式这样做吗?

Should I be doing this another way?

推荐答案

Popen.communicate 将在完成时设置 returncode 属性(*).以下是相关文档部分:

Popen.communicate will set the returncode attribute when it's done(*). Here's the relevant documentation section:

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).

所以你可以这样做(我没有测试但它应该可以工作):

So you can just do (I didn't test it but it should work):

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

<小时>

(*) 发生这种情况是因为它的实现方式:在设置线程读取子流之后,它只调用wait.

这篇关于使用Python子进程通信方法时如何获取退出代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆