我想检查一个子进程是否已经成功执行或者失败了。目前我想出了一种解决方案,但我不确定它是否正确可靠。每个进程保证只将其错误输出到标准错误流(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_output
方法。您可以从中获取stdout和stderr,仍然可以捕获错误。请参见此处:https://docs.python.org/2/library/subprocess.html#subprocess.check_output - elParaguayo