【问题标题】:Python's subprocess.getoutput with non-UTF-8 outputPython 的 subprocess.getoutput 与非 UTF-8 输出
【发布时间】:2015-12-06 03:20:01
【问题描述】:

有没有办法让 subprocess.getoutput 处理不是有效 UTF-8 的输出?如果命令的输出返回非 UTF-8 字符,则会引发异常。但是,该函数似乎没有编码参数。

File "foo.py", line 104, in <module>
  OutText = subprocess.getoutput(TheCmd)
File "/usr/local/Cellar/python3/3.5.0/Frameworks/Python.framework/Versions/3.5/lib/python3.5/subprocess.py", line 827, in getoutput
  return getstatusoutput(cmd)[1]
. . .
File "/usr/local/Cellar/python3/3.5.0/Frameworks/Python.framework/Versions/3.5/lib/python3.5/codecs.py", line 321, in decode
  (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xcc in position 1495: invalid continuation byte

【问题讨论】:

  • 可以用try-except 块包裹它并且只超过这个例外。
  • 输出的编码依赖于执行的命令和运行的平台,不依赖于函数subprocess.getoutput()。

标签: python utf-8


【解决方案1】:

您可以尝试另一个带有选项test=True 的命令subprocess.check_output。这个函数的结果是字节。然后您可以使用正确的编解码器手动解码字节以获得字符串结果。像这样:

import subprocess

cmd = "svn log"
result_bytes = subprocess.check_output(cmd, text=False)
result = result_bytes.decode("gb2312")
print(result)

【讨论】:

    猜你喜欢
    • 2016-03-11
    • 2016-05-03
    • 1970-01-01
    • 2015-10-26
    • 1970-01-01
    • 1970-01-01
    • 2013-10-11
    • 2014-04-16
    • 2015-06-04
    相关资源
    最近更新 更多