os.popen().read()-Charmap解码错误 [英] os.popen().read() - charmap decoding error

查看:1020
本文介绍了os.popen().read()-Charmap解码错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了 UnicodeDecodeError:"charmap"编解码器无法解码位置Y的字节X:字符映射为< undefined> .虽然错误消息相似,但是代码却完全不同,因为在这个问题中我使用的是os.popen而不是open.我不能用其他问题的答案来解决这个问题.

I have already read UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined>. While the error message is similar, the code is completely different, because I use os.popen in this question, not open. I cannot use the answers from the other questions to solve this problem.

output = os.popen("dir").read()

本行应该将命令"dir"的输出分配给变量"output",导致此错误:

This line, which is supposed to assign the output of command "dir" to variable "output", is causing this error:

'charmap' codec can't decode byte 0x88 in position 260: character maps to <undefined>

我认为可能会发生这种情况,因为文件夹中的某些文件的名称中包含诸如ł,±,ęć之类的字母.我不知道如何解决这个问题.

I think this might be happenning because some files in the folder contain letters such as ł, ą, ę and ć in their names. I have no idea how to fix this though.

推荐答案

os.popen只是subprocess.Popenio.TextIOWrapper对象的包装:

返回的文件对象读取或写入文本字符串,而不是字节.

The returned file object reads or writes text strings rather than bytes.

如果Python的默认编码对您不起作用,则应直接使用subprocess.Popen.

If Python's default encoding doesn't work for you, you should use subprocess.Popen directly.

潜在的问题是,即使输出到管道,cmd也会默认写入ansi垃圾.此行为可能取决于您的Windows版本.

The underlying issue is that cmd writes ansi garbage by default, even when the output is to a pipe. This behavior may depend on your Windows version.

您可以通过将/U标志传递给cmd来解决此问题:

You can fix this by passing /U flag to cmd:

p = subprocess.Popen('cmd /u /c dir', stdout=subprocess.PIPE)
result = p.communicate()
text = result[0].decode('u16')

这篇关于os.popen().read()-Charmap解码错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆