【问题标题】:subprocess Popen - decode子进程 Popen - 解码
【发布时间】:2021-08-31 12:46:35
【问题描述】:

在我的脚本中,我使用它来解码为 utf-8:

result = subprocess.run(['command'], stdout=subprocess.PIPE).stdout.decode('utf-8')

现在我需要更改需要使用管道的命令,因此根据我发现的几个示例,我需要使用 subprocess.Popen 而不是 subprocess.run。所以我有这样的事情:

    r1 = subprocess.Popen(['command1'], stdout=subprocess.PIPE)
    r2 = subprocess.Popen(['command2'], stdin=r1.stdout, stdout=subprocess.PIPE)
    r3 = subprocess.Popen(['command3'], stdin=r2.stdout, stdout=subprocess.PIPE)
    result = r3.stdout

但是,在这种情况下,我无法添加到末尾 stdout.decode('utf-8') 因为我收到错误

AttributeError: '_io.BufferedReader' object has no attribute 'decode'

谁能帮帮我,我怎样才能把它解码成utf8?

【问题讨论】:

  • 对不起,我犯了一个错误。现在应该没问题了。但是我的问题没有解决。我刚刚在这里复制了错误的部分。
  • 只需subprocess.running 最终命令应该可以工作。
  • r3.stdout.read() 应该是文本本身。您还可以将编码或文本参数传递给 Popen docs.python.org/3/library/subprocess.html#subprocess.Popen

标签: python subprocess decode


【解决方案1】:

如果你需要读取输出你可以试试

op = subprocess.check_output(
        command, shell=True, stderr=subprocess.STDOUT)


result = op.decode()

【讨论】:

  • 这并没有真正展示如何在 Python 中正确执行此操作。如果您想放弃控制权,将工作委派给 shell 可能是一种可行的方法,但如果 OP 询问是否使用 Popen,那么您应该回答这个问题。 (subprocess.run() 做所有check_output 做的事情。)
【解决方案2】:

当你运行Popen 时,你必须自己做管道。

很简单,你要添加

stdout, stderr = r3.communicate()

允许r3(以及其他两个进程)完成。

你还应该收获你开始的其他进程。

r1.wait()
r2.wait()

最后,您可以decode您阅读的文字。

print(stdout.decode('utf-8'))

但是,您可能希望避免从 Python 运行复杂的管道。通常,您可以用本机 Python 代码替换简单的 shell 实用程序。

另一方面,如果您想尽可能少地编写代码,则最好使用 shell=True 在单个 shell 命令中运行所有内容(使用 usual caveats)。

【讨论】:

    猜你喜欢
    • 2018-12-05
    • 2014-03-28
    • 1970-01-01
    • 2014-09-15
    • 1970-01-01
    • 1970-01-01
    • 2012-03-03
    • 2011-10-02
    • 2011-08-05
    相关资源
    最近更新 更多