【问题标题】:Can I have subprocess.call write the output of the call to a string?我可以让 subprocess.call 将调用的输出写入字符串吗?
【发布时间】:2011-08-19 15:18:01
【问题描述】:

我想做 subprocess.call,并将调用的输出转换成一个字符串。我可以直接执行此操作,还是需要将其通过管道传输到文件中,然后从中读取?

换句话说,我可以以某种方式将 stdout 和 stderr 重定向到一个字符串吗?

【问题讨论】:

标签: python subprocess


【解决方案1】:

在 Python 3.7+ 中使用 text=True

在较新版本的 Python 中,您可以简单地使用 text=True 来获取字符串返回值:

>>> import subprocess
>>> subprocess.check_output(["echo", "hello"], text=True)
'hello\n'

这里是what the docs say

如果指定了encodingerrors,或者text 为真,则stdin、stdout 和stderr 的文件对象将使用指定的encodingerrorsio.TextIOWrapper 默认以文本模式打开. universal_newlines 参数等价于 text 并提供向后兼容性。默认情况下,文件对象以二进制模式打开。

【讨论】:

    【解决方案2】:

    这是 mantazer 对 python3 的回答的扩展。你仍然可以在 python3 中使用subprocess.check_output 命令:

    >>> subprocess.check_output(["echo", "hello world"])
    b'hello world\n'
    

    但是现在它给了我们一个字节串。要获得真正的 python 字符串,我们需要使用 decode:

    >>> subprocess.check_output(["echo", "hello world"]).decode(sys.stdout.encoding)
    'hello world\n'
    

    使用sys.stdout.encoding 而不仅仅是默认的UTF-8 作为编码应该可以在任何操作系统上运行(至少在理论上)。

    使用.strip() 可以轻松删除尾随的换行符(和任何其他额外的空格),因此最终命令是:

    >>> subprocess.check_output(["echo", "hello world"]
                                ).decode(sys.stdout.encoding).strip()
    'hello world'
    

    【讨论】:

    • 如何将输出写入文件?我尝试使用重定向“>”在命令本身中传递文件名,但是当 python 代码中的下一行尝试查看内容时,它是空的
    • @SanjeevkumarM 使用stdout 参数,给它一个要写入的文件object(例如,由open 创建,确保之后关闭它)。
    • 这太完美了。谢谢。
    【解决方案3】:

    subprocess 模块提供了一个方法 check_output(),它运行带有参数(如果有)的提供的命令,并将其输出作为字节字符串返回。

    output = subprocess.check_output(["echo", "hello world"])
    print output
    

    上面的代码将打印hello world

    请参阅文档:https://docs.python.org/2/library/subprocess.html#subprocess.check_output

    【讨论】:

    • 如何将输出写入文件?我尝试使用重定向“>”在命令本身中传递文件名,但是当 python 代码中的下一行尝试查看内容时,它是空的
    【解决方案4】:

    不,您不能将 subprocess.call() 的输出直接读入字符串。

    为了将命令的输出读入字符串,需要使用 subprocess.Popen(),例如:

    >>> cmd = subprocess.Popen('ls', stdout=subprocess.PIPE)
    >>> cmd_out, cmd_err = cmd.communicate()
    

    cmd_out 将包含带有命令输出的字符串。

    【讨论】:

      【解决方案5】:

      subprocess.call() 采用与subprocess.Popen() 相同的参数,其中包括stdoutstderr 参数。有关详细信息,请参阅文档。

      【讨论】:

      • 在线浏览文档对我来说不是很清楚,您能否提供一个示例,就像使用 Popen 的其他答案一样。或发布链接,其中包含一个明确的示例,例如当 stdout=subprocess.PIPE 时如何获取 stdout 值。答案和 Popen 答案一样吗?
      • 实际上是一样的,因为两个函数都采用相同的参数。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-26
      • 2010-12-30
      • 2011-05-03
      • 1970-01-01
      • 1970-01-01
      • 2011-01-20
      相关资源
      最近更新 更多