下面的代码将使Python以utf-8的形式输出到控制台,即使在Windows上也是如此。
控制台将在Windows 7上很好地显示字符,但在Windows XP上,它将无法很好地显示字符,但至少它可以工作,而且最重要的是,您的脚本在所有平台上的输出都是一致的。您将能够将输出重定向到文件。
下面的代码在Windows上用python 2.6进行了测试。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import codecs, sys
reload(sys)
sys.setdefaultencoding('utf-8')
print sys.getdefaultencoding()
if sys.platform == 'win32':
try:
import win32console
except:
print "Python Win32 Extensions module is required.\n You can download it from https://sourceforge.net/projects/pywin32/ (x86 and x64 builds are available)\n"
exit(-1)
# win32console implementation of SetConsoleCP does not return a value
# CP_UTF8 = 65001
win32console.SetConsoleCP(65001)
if (win32console.GetConsoleCP() != 65001):
raise Exception ("Cannot set console codepage to 65001 (UTF-8)")
win32console.SetConsoleOutputCP(65001)
if (win32console.GetConsoleOutputCP() != 65001):
raise Exception ("Cannot set console output codepage to 65001 (UTF-8)")
#import sys, codecs
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
sys.stderr = codecs.getwriter('utf8')(sys.stderr)
print "This is an Ðä¹Î±mpÙ¡È testing Unicode support using Arabic, Latin, Cyrillic, Greek, Hebrew and CJK code points.\n"