gpt4 book ai didi

具有非 UTF-8 输出的 Python 的 subprocess.getoutput

转载 作者:行者123 更新时间:2023-12-05 07:52:08 24 4
gpt4 key购买 nike

有没有办法让 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

最佳答案

您可以尝试另一个带有选项 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)

关于具有非 UTF-8 输出的 Python 的 subprocess.getoutput,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34113630/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com