【问题标题】:How to return encoded value using subprocess.Popen in Python?如何在 Python 中使用 subprocess.Popen 返回编码值?
【发布时间】:2018-07-18 12:03:30
【问题描述】:

谁能告诉我如何编码 return 语句,以便它可以解码它。 或者需要更改什么来获取编码值。

代码

def run_process(cmd_args):
    with subprocess.Popen(cmd_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as proc:
        return proc.communicate()


res = run_process(cmd_args);
print(res)
print(res.decode("utf-8"))

输出

print(res.decode("utf-8"))
AttributeError: 'tuple' object has no attribute 'decode'

【问题讨论】:

    标签: python-3.x subprocess popen with-statement


    【解决方案1】:

    Popen.communicate返回一个(stdout, stderr)的元组,所以你需要这样对待返回值:

    stdout, stderr = run_process(cmd_args);
    print(stdout)
    print(stdout.decode("utf-8"))
    

    请阅读Popen.communicate's documentation了解更多详情。

    【讨论】:

    • 明白了! @blhsing,非常感谢 stdout,stderr = run_process(cmd_args);这对我有帮助。
    【解决方案2】:

    而不是返回 proc.communicate(),而是返回 proc.communicate()[0]。 由于 proc.communicate() 是输出和错误列表,您似乎只需要输出部分

    【讨论】:

      猜你喜欢
      • 2019-05-26
      • 2016-03-12
      • 1970-01-01
      • 2014-11-23
      • 2021-01-02
      • 1970-01-01
      • 1970-01-01
      • 2020-01-30
      • 1970-01-01
      相关资源
      最近更新 更多