我想检查子流程是成功执行还是失败。目前我想出了一个解决方案,但我不确定它是否正确可靠。是否保证每个进程仅将其错误输出到 stderr 恭敬地 stdout
:
注意:我对重定向/打印输出不感兴趣。我已经知道该怎么做了。
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
原文由 Zingam 发布,翻译遵循 CC BY-SA 4.0 许可协议
您需要对过程的输出做些什么吗?
check_call
方法在这里可能会有用。请在此处查看 python 文档: https ://docs.python.org/2/library/subprocess.html#subprocess.check_call然后您可以按如下方式使用它:
但是,这依赖于
command
成功完成返回退出代码 0,错误返回非零值。如果您还需要捕获输出,那么
check_output
方法可能更合适。如果您也需要,仍然可以重定向标准错误。请参阅此处的文档: https ://docs.python.org/2/library/subprocess.html#subprocess.check_output