【问题标题】:python getoutput() equivalent in subprocess [duplicate]子进程中的python getoutput()等价物[重复]
【发布时间】:2011-10-03 05:10:27
【问题描述】:

我想在 python 脚本中获取一些 shell 命令的输出,例如 lsdf。我看到 commands.getoutput('ls') 已被弃用,但 subprocess.call('ls') 只会让我得到返回码。

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

【问题讨论】:

    标签: python shell command subprocess


    【解决方案1】:

    使用subprocess.Popen

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

    请注意,通信会阻塞,直到进程终止。如果您需要在输出终止之前输出,您可以使用 process.stdout.readline()。如需更多信息,请参阅documentation

    【讨论】:

    • subprocess 示例的 Python 2.7 版本的正确当前文档链接是:docs.python.org/library/…;对于 Python 3.2,docs.python.org/py3k/library/…
    • 您可能需要将 subprocess.communicate() 替换为 process.communicate() - 您可能还需要通过执行 process.returncode 来获得子进程退出代码
    • 我没有注意到我写的是子进程而不是进程。固定。
    • 哪些类型有误?它们是常规字符串还是数组或字典?
    • out 工作正常,但err 将未初始化并且错误输出会打印到屏幕上。除了 stdout 之外,您还必须指定 stderr=subprocess.PIPE 才能获得标准错误。
    【解决方案2】:

    对于 Python >= 2.7,使用 subprocess.check_output()

    http://docs.python.org/2/library/subprocess.html#subprocess.check_output

    【讨论】:

    • 技术上应该是subprocess.check_output(cmd, shell=True)
    • shell真假有什么区别?
    • 我认为它启用了“shell 特定功能”,如文件通配、管道等...
    • @RickyWilson 命令像 'dir' (或 'ls' )一样被嵌入到 shell 中,除非你传入 shell=True 以及其他特定于 shell 的功能,否则你会发现错误并且不会被发现就像上面所说的管道。否则,子进程 cmd 列表应该是有效的文件路径及其参数。此外,当 shell=True 时,您可能会产生允许的命令的最大字符串长度,具体取决于平台,而 shell=False 将允许消化更长的命令,而不是通常允许手动输入的 shell。
    【解决方案3】:

    要使用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
    

    【讨论】:

      猜你喜欢
      • 2013-11-04
      • 2011-12-15
      • 1970-01-01
      • 2011-03-15
      • 2011-09-12
      • 2013-06-21
      • 2010-11-27
      • 2018-04-16
      • 2014-02-15
      相关资源
      最近更新 更多