【发布时间】:2012-04-29 10:23:26
【问题描述】:
我在 Python 2.* 中发现了这个对 getstatusoutput() 函数的出色替换,它在 Unix 和 Windows 上同样适用。但是,我认为output 的构造方式有问题。它只返回输出的最后一行,但我不知道为什么。任何帮助都会很棒。
def getstatusoutput(cmd):
"""Return (status, output) of executing cmd in a shell."""
"""This new implementation should work on all platforms."""
import subprocess
pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True, universal_newlines=True)
output = "".join(pipe.stdout.readlines())
sts = pipe.returncode
if sts is None: sts = 0
return sts, output
【问题讨论】:
-
为什么不在 try 块中使用
subprocess.check_call?您可以在except部分中获取返回码(如果它不为零)。 -
即使返回码为0,如果我想要输出怎么办?