我已经读过UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined> .虽然错误信息相似,但代码完全不同,因为我在这道题中使用的是os.popen
,而不是open
。我无法使用其他问题的答案来解决这个问题。
output = os.popen("dir").read()
本应将命令“dir”的输出分配给变量“output”的这一行导致了此错误:
'charmap' codec can't decode byte 0x88 in position 260: character maps to <undefined>
我认为这可能会发生,因为文件夹中的某些文件的名称中包含 ł、ą、ę 和 ć 等字母。不过我不知道如何解决这个问题。
最佳答案
os.popen
只是 subprocess.Popen
和 io.TextIOWrapper
对象的包装器:
The returned file object reads or writes text strings rather than bytes.
如果 Python 的默认编码不适合你,你应该直接使用 subprocess.Popen
。
潜在的问题是 cmd 默认写入 ansi 垃圾,即使输出到管道也是如此。此行为可能取决于您的 Windows 版本。
您可以通过将 /U
标志传递给 cmd 来解决此问题:
p = subprocess.Popen('cmd /u /c dir', stdout=subprocess.PIPE)
result = p.communicate()
text = result[0].decode('u16')
关于python - os.popen().read() - charmap 解码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42033334/