quot;subprocess.Popenquot; - checking for success and errors(“子进程.Popen- 检查成功和错误)
问题描述
我想检查一个子进程是成功完成还是失败了.目前我已经提出了一个解决方案,但我不确定它是否正确和可靠.是否保证每个进程仅将其错误输出到 stderr 尊重 stdout
:
I want to check if a subprocess has finished execution successfully or failed. Currently I have come up with a solution but I am not sure if it is correct and reliable. Is it guaranteed that every process outputs its errors only to stderr respectfully to stdout
:
注意:我对重定向/打印输出不感兴趣.我已经知道该怎么做了.
Note: I am not interested in just redirecting/printing out the output. That I know already how to do.
pipe = subprocess.Popen(command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True)
if "" == pipe.stdout.readline():
print("Success")
self.isCommandExectutionSuccessful = True
if not "" == pipe.stderr.readline():
print("Error")
self.isCommandExectutionSuccessful = True
或者:
if "" == pipe.stdout.readline():
print("Success")
self.isCommandExectutionSuccessful = True
else:
print("Error")
self.isCommandExectutionSuccessful = False
和:
if not "" == pipe.stderr.readline():
print("Success")
self.isCommandExectutionSuccessful = True
else:
print("Error")
self.isCommandExectutionSuccessful = False
推荐答案
你需要对进程的输出做些什么吗?
Do you need to do anything with the output of the process?
check_call
方法在这里可能很有用.在此处查看 python 文档:https://docs.python.org/2/library/subprocess.html#subprocess.check_call
The check_call
method might be useful here. See the python docs here: https://docs.python.org/2/library/subprocess.html#subprocess.check_call
然后您可以按如下方式使用它:
You can then use this as follows:
try:
subprocess.check_call(command)
except subprocess.CalledProcessError:
# There was an error - command exited with non-zero code
但是,这依赖于 command
返回退出代码 0 表示成功完成,返回非零值表示错误.
However, this relies on command
returning an exit code of 0 for succesful completion and a non-zero value for an error.
如果您还需要捕获输出,那么 check_output
方法可能更合适.如果您也需要,仍然可以重定向标准错误.
If you need to capture the output as well, then the check_output
method may be more appropriate. It is still possible to redirect the standard error if you need this as well.
try:
proc = subprocess.check_output(command, stderr=subprocess.STDOUT)
# do something with output
except subprocess.CalledProcessError:
# There was an error - command exited with non-zero code
在此处查看文档:https://docs.python.org/2/library/subprocess.html#subprocess.check_output
这篇关于“子进程.Popen"- 检查成功和错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:“子进程.Popen"- 检查成功和错误
基础教程推荐
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 筛选NumPy数组 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01