2024-06-26 18:07:42 发布
网友
使用Python的subprocess模块和communicate()方法时,如何检索退出代码?
subprocess
communicate()
相关代码:
import subprocess as sp data = sp.Popen(openRTSP + opts.split(), stdout=sp.PIPE).communicate()[0]
我应该换一种方式吗?
^{}。如果子进程写入标准输出/错误和/或从标准输入读取,并且没有对等进程,则子进程将被阻止。
完成后,Popen.communicate将设置returncode属性(*)。以下是相关文档部分:
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。
wait
您应该首先确保进程已完成运行,并且已使用.wait方法读取了返回代码。这将返回代码。如果您希望以后访问它,它将作为.returncode存储在Popen对象中。
.wait
.returncode
Popen
^{} 。如果子进程写入标准输出/错误和/或从标准输入读取,并且没有对等进程,则子进程将被阻止。
完成后,
Popen.communicate
将设置returncode
属性(*)。以下是相关文档部分:所以你可以这样做(我没有测试,但应该可以):
(*)这是因为它的实现方式:在设置线程以读取子流之后,它只调用
wait
。您应该首先确保进程已完成运行,并且已使用
.wait
方法读取了返回代码。这将返回代码。如果您希望以后访问它,它将作为.returncode
存储在Popen
对象中。相关问题 更多 >
编程相关推荐