我发现了这个很棒的替代品getstatusoutput()
Python 2.* 中的函数在 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
这里面有一个bug。
通话:
pipe = subprocess.Popen(...)
启动该过程。该行:
output = "".join(pipe.stdout.readlines())
读取进程的标准输出(如果有错误输出,它可能会被阻塞,但由于您没有重定向标准错误,这是安全的;在更一般的情况下,您需要使用.communicate()
功能以避免可能的楔入)。您可能会想:好吧,现在我已经阅读了所有输出,子流程显然已经完成,所以pipe.returncode
应设置。但事实上,如果你替换:
sts = pipe.returncode
if sts is None: sts = 0
使用包含某种诊断的代码(或者只是完全删除第二行),您会发现,至少有时在某些系统上,sts
is None
。原因是,subprocess
模块还没有机会检索它。您应该将这些行替换为:
sts = pipe.wait()
收集结果并消除对is None
测试。 (可以安全地拨打电话.wait()
即使你用过.communicate()
和/或已经调用.wait()
.)
The "".join(...)
可以通过使用以下方法稍微更有效地完成:
output = pipe.stdout.read()
话虽如此,它确实为我提供了完整的输出。也许您正在阅读的内容仅使用'\r'
对于换行符,并且您的 Python 是在没有通用换行符支持的情况下构建的? (如果我运行的东西产生\r
-for-newline 我仍然得到所有行,由实际的换行符分隔。)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)