I'm using Python 2.6 on Windows 7
我从这里借了一些代码: Python, Unicode, and the Windows console
我的目标是能够在windows控制台中显示uft-8字符串。
显然在Python2.6中
sys.setdefaultencoding()
不再支持
然而,在尝试使用它之前,我编写了reload(sys),它神奇地没有出错。
这段代码不会出错,但它显示的是有趣的字符,而不是日语文本。 我认为问题是因为我没有成功更改windows控制台的代码页。
这些都是我的尝试,但都不管用:
reload(sys)
sys.setdefaultencoding('utf-8')
print os.popen('chcp 65001').read()
sys.stdout.encoding = 'cp65001'
也许您可以使用win32console更改代码页? 我尝试了我链接的网站上的代码,但也在win32console上出错了。。也许那个代码已经过时了。
这是我的代码,它不会出错,但会打印出有趣的字符:
#coding=<utf8>
import os
import sys
import codecs
reload(sys)
sys.setdefaultencoding('utf-8')
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
sys.stderr = codecs.getwriter('utf8')(sys.stderr)
#print os.popen('chcp 65001').read()
print(sys.stdout.encoding)
sys.stdout.encoding = 'cp65001'
print(sys.stdout.encoding)
x = raw_input('press enter to continue')
a = 'こんにちは世界'#.decode('utf8')
print a
x = raw_input()
永远不要使用
setdefaultencoding
。如果要将unicode字符串写入stdio,请显式编码它们。与setdefaultencoding
乱搞会导致stdlib模块和第三方模块以可怕的微妙方式崩溃,因为它们允许str
和unicode
之间在不应该发生的情况下进行隐式转换。是的,问题很可能是您的代码页设置不正确。但是,使用
os.popen
不会更改代码页;它会生成一个新的shell,更改其代码页,然后立即退出而不会影响控制台。我个人对windows不是很熟悉,所以我无法告诉您如何从python程序中更改控制台的代码页。如前所述,通过来自python的utf-8正确显示unicode数据的方法是在打印字符串之前显式地对其进行编码:
print s.encode('utf-8')
更改控制台代码页是不必要的,也不起作用(特别是,将其设置为65001会运行到Python bug)。请参阅this question了解详细信息,以及如何将Unicode字符打印到控制台,而不考虑代码页。
我知道你说你使用的是Python2.6,但是如果你能使用Python3.3,你会发现它最终得到了支持。
在启动Python之前使用命令
chcp 65001
。见http://docs.python.org/dev/whatsnew/3.3.html#codecs
在Python 3.6中,甚至不再需要使用
chcp
命令,因为Python完全绕过字节级控制台接口,而是使用本机Unicode接口。见PEP 528: Change Windows console encoding to UTF-8。正如@mbom007在评论中指出的,确保控制台配置了支持您试图显示的字符的字体也很重要。
相关问题 更多 >
编程相关推荐