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

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


相关代码:


import subprocess as sp

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

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


人到中年有点甜
浏览 561回答 3
3回答

慕盖茨4494581

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 spchild = sp.Popen(openRTSP + opts.split(), stdout=sp.PIPE)streamdata = child.communicate()[0]rc = child.returncode(*)发生这种情况的原因是它的实现方式:设置线程以读取子流后,它仅调用wait。

慕标琳琳

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

小唯快跑啊

.poll() 将更新返回码。尝试child = sp.Popen(openRTSP + opts.split(), stdout=sp.PIPE)returnCode = child.poll()另外,在.poll()调用之后,该对象中的返回码可用child.returncode。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python