Python 2.7:在Windows控制台中输出utf-8

我们说

s = u"test\u0627\u0644\u0644\u0647 \u0623\u0643\u0628\u0631\u7206\u767A\u043E\u043B\u043E\u043B\u043E" 

如果我尝试直接打印它,

 >>> print s Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeEncodeError: 'cp932' codec can't encode character u'\u0627' in position 4: illegal multibyte sequence 

所以我把这个控制台从Python变成了UTF-8(否则它不会理解我的input)。

 import win32console win32console.SetConsoleOutputCP(65001) win32console.SetConsoleCP(65001) 

然后输出编码为utf-8的string,因为Python不知道chcp 65001是UTF-8(一个已知的bug )。

 >>> print s.encode('utf-8') testالله أكبر爆発ололоTraceback (most recent call last): File "<stdin>", line 1, in <module> IOError: [Errno 0] Error 

正如你所看到的,它打印成功,直到它命中一个换行符,然后它会抛出一个IOError。

以下解决方法工作:

 def safe_print(str): try: print str.encode('utf-8') except: pass print >>> safe_print(s) testالله أكبر爆発ололо 

但是一定有更好的办法。 有什么build议么?

python utf8 windows中 搜索带来的第一个结果是在Windows XP上使用UTF8打印python的问题,这个控制台描述了从Python打印Windows中的utf8的问题。

我没有在Windows上测试它,但在这里你可以得到一个小的初始化脚本为win / linux来正确设置输出编码,包括日志接口等。该模块还使输出颜色(包括更新'日志'界面)? 但是你可以很容易地把它们关掉:-)。

如何调用非彩色变体:

 #!/usr/bin/env python # -*- coding: utf-8 -*- from setupcon import setup_console setup_console('utf-8', False) 

和彩色变体:

 import setupcon setupcon.setup_console() import logging #... if setupcon.ansi: logging.getLogger().addHandler(setupcon.ColoredHandler()) 

如果解决方案适用于您,您可以阅读这里的文档: http : //habrahabr.ru/blogs/python/117236/ ,在俄罗斯,或我/有人可以翻译它为您需求:-)。