Python中subprocess模块的getoutput()等效函数是什么?

79

我希望能够在Python脚本中获取一些shell命令(如lsdf)的输出。我发现commands.getoutput('ls')已被弃用,但subprocess.call('ls')只能获取返回代码。

我希望有一些简单的解决方案。

3个回答

116

使用 subprocess.Popen

import subprocess
process = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = process.communicate()
print(out)

请注意,communicate 命令会一直阻塞直到进程终止。如果您需要在进程终止之前获取输出,可以使用process.stdout.readline()。更多信息请参见文档


Python 2.7版本的subprocess示例的正确文档链接是: http://docs.python.org/library/subprocess.html#replacing-older-functions-with-the-subprocess-module;对于Python 3.2,链接是http://docs.python.org/py3k/library/subprocess.html#replacing-older-functions-with-the-subprocess-module。 - Ned Deily
5
你可能需要将subprocess.communicate()替换为process.communicate() - 你还可以通过process.returncode获取subprocess的退出码。 - Cinquo
我没有注意到我写成了subprocess而不是process。已修复。 - Michael Smith
out和err是什么类型?它们是普通字符串还是数组或字典? - scottysseus
3
对于 out 参数,一切正常,但 err 将未被初始化且错误输出将被打印到屏幕上。你需要除了指定 stdout 之外还要指定 stderr=subprocess.PIPE 才能获取标准错误信息。 - Gerrit-K
“out”是什么类型?它看起来像是某种类型的对象,因为我不能像字符串一样将其写入文件 subprocess.Popen(["echo", out, ">>", "/home/ec2-user/output_test.sh"], stdout=subprocess.PIPE) - Kyle Bridenstine

56

8
从技术上讲,应该是 subprocess.check_output(cmd, shell=True) - Cerin
1
什么是shell中True和False的区别? - Ricky Wilson
3
我认为它使得“特定于 shell 的功能”变得可用,如文件通配、管道等。 - Rafael T
1
@RickyWilson 命令被嵌入到 shell 中,例如 'dir'(或 'ls'),如果不传递 shell=True 参数,则会出现错误并且找不到该命令,同时还需要传递其他特定于 shell 的功能,如上所述的管道。否则,subprocess cmd 列表应该是一个有效的文件路径及其参数。另外,当 shell=True 时,您可能会遇到命令允许的最大字符串长度,这取决于平台,而 shell=False 则允许消化比 shell 正常允许手动输入的更长的命令。 - Jordan Stefanelli

12

使用subprocess.check_output()捕获错误时,您可以使用CalledProcessError。 如果您想将输出作为字符串使用,请从字节码解码。

# \return String of the output, stripped from whitespace at right side; or None on failure.
def runls():
    import subprocess
    try:
        byteOutput = subprocess.check_output(['ls', '-a'], timeout=2)
        return byteOutput.decode('UTF-8').rstrip()
    except subprocess.CalledProcessError as e:
        print("Error in ls -a:\n", e.output)
        return None

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接