我要检查子进程是否已成功完成执行或失败。目前我已经提出了一个解决方案,但我不确定它是否正确和可靠。是否保证每个进程只将其错误分别输出到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
带有check-on返回代码、stdout和stderr的完整解决方案:
印刷品:
你需要对过程的输出做些什么吗?
在这里,
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
您可以使用check_call()方法检查进程的返回代码。 如果进程返回非零值,则将引发调用进程错误。
相关问题 更多 >
编程相关推荐