python win32console_python、unicode和windows控制台

这段Python代码确保在Windows环境下,包括XP和7,脚本能以UTF-8编码输出到控制台,保持一致的输出效果。通过win32console模块设置控制台输入和输出代码页为65001(UTF-8),并处理可能的异常。这样,即便在不支持完整Unicode显示的系统中,脚本仍能正常工作。
摘要由CSDN通过智能技术生成

下面的代码将使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"

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值