如何解决UnicodeDecodeError: 'charmap' 编解码器无法解码位置 28 中的字节 0x81:字符映射到 <undefined>
我有一个用于 Windows 系统的脚本来获取该系统上所有已安装的软件包,我需要确保它可以在所有语言环境中工作。
现在,我有以下几点:
>>> response = os.popen("dism /online /get-packages").read()
Traceback (most recent call last):
File "<stdin>",line 1,in <module>
File "C:\Users\abc\Python\lib\encodings\cp1252.py",line 23,in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 28: character maps to <undefined>
我阅读了很多其他类似的 SO 线程并尝试这样做:
>>> response = subprocess.Popen("dism /online /get-packages",shell=True,stdout=subprocess.PIPE).stdout
(1)
>>> print(response.read().decode())
Traceback (most recent call last):
File "<stdin>",in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x81 in position 28: invalid start byte
(2)
>>> import locale
>>> locale.getpreferredencoding()
'cp1252'
>>> print(response.read().decode('cp1252'))
Traceback (most recent call last):
File "<stdin>",in <module>
File "C:\Users\abc\Python\lib\encodings\cp1252.py",line 15,errors,decoding_table)
UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 28: character maps to <undefined>
仅供参考,此特定示例适用于(系统的默认语言为德语):
>>> print(response.read().decode('cp850'))
[prints output correctly]
我可以在这里做什么才能确信我的程序不会在使用不同语言的系统上崩溃?
(Python 3.6+)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。