让python在Windows XP上使用控制台以UTF8进行打印

Phi*_*e F 11 python windows unicode windows-xp utf-8

我想在Windows XP上配置我的控制台以支持UTF8并让python检测并使用它.

到目前为止,我的尝试:

C:\Documents and Settings\Philippe>C:\Python25\python.exe
Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print u'é'
é
>>> import sys
>>> sys.stdout.encoding
'cp437'
>>> quit()
Run Code Online (Sandbox Code Playgroud)

所以,默认情况下我在cp437并且python检测到就好了.

C:\Documents and Settings\Philippe>chcp 65001
Active code page: 65001

C:\Documents and Settings\Philippe>python
Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.stdout.encoding
'cp65001'
>>> print u'é'
C:\Documents and Settings\Philippe>
Run Code Online (Sandbox Code Playgroud)

好像用UTF8打印让python崩溃了......

bob*_*nce 8

我想在Windows XP上配置我的控制台以支持UTF8

我不认为这会发生.

65001代码页是错误的; 一些stdio调用行为不正确并打破了许多工具.您可以手动将cp65001注册为编码:

def cp65001(name):
    if name.lower()=='cp65001':
        return codecs.lookup('utf-8')

codecs.register(cp65001)
Run Code Online (Sandbox Code Playgroud)

这允许您print u'some unicode string',它不允许您在该Unicode字符串中写入非ASCII字符.当您尝试将非ASCII UTF-8序列直接写为字节字符串时,您会得到相同的奇怪错误(IOError 0等).

不幸的是,UTF-8是Windows下的二等公民.NT的Unicode模型是在UTF-8存在之前制定的,因此你需要在任何你想要一致的Unicode的地方使用每个代码单元编码两个字节(UTF-16,最初是UCS-2).使用字节字符串,就像许多便携式应用程序和用C编写的语言(如Python)一样stdio,不适合该模型.

并重写Python以使用Windows Unicode控制台调用(如WriteConsoleW)而不是便携式C stdio调用不适合使用像管道和重定向到文件的shell技巧.(更不用说你仍然需要从默认终端字体更改为TTF,然后才能看到结果正常工作......)

最终,如果您需要一个支持基于stdio的应用程序的UTF-8支持的命令行,那么您可能最好使用故意支持它的Windows控制台的替代方案,例如Cygwin,或Python的IDLE或pywin32的PythonWin.