Python';s subprocess.getoutput与非UTF-8输出
有没有办法让subprocess.getoutput处理无效的UTF-8输出?如果命令的输出返回非UTF-8字符,则会引发异常。但是,函数似乎没有编码参数Python';s subprocess.getoutput与非UTF-8输出,python,utf-8,Python,Utf 8,有没有办法让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/pytho
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
文件“foo.py”,第104行,在
OutText=subprocess.getoutput(CMD)
getoutput中的文件“/usr/local/ceral/python3/3.5.0/Frameworks/Python.framework/Versions/3.5/lib/python3.5/subprocess.py”,第827行
返回getstatusoutput(cmd)[1]
. . .
文件“/usr/local/ceral/python3/3.5.0/Frameworks/Python.framework/Versions/3.5/lib/python3.5/codecs.py”,第321行,解码
(结果,消耗)=自身缓冲区解码(数据,自身错误,最终)
UnicodeDecodeError:“utf-8”编解码器无法解码1495位置的字节0xcc:无效的连续字节
可以使用try except
块将其包装,并仅超越此异常。输出的编码取决于执行的命令和运行平台,而不依赖于函数subprocess.getoutput()。