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"- 检查成功和错误
基础教程推荐
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
