如何在Windows控制台中显示utf-8 [英] How to display utf-8 in windows console

查看:691
本文介绍了如何在Windows控制台中显示utf-8的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我在Windows 7上使用Python 2.6


我从这里借了一些代码:
Python,Unicode和Windows控制台



我的目标是能够在Windows控制台中显示uft-8字符串。



在python 2.6中,


sys.setdefaultencoding()


不再支持



然而,我在我尝试使用它之前写了reload(sys),它奇迹般没有错误。



这段代码不会报错,但它显示有趣的字符,而不是日语文本。
我相信问题是因为我没有成功更改Windows控制台的代码页。

这是我的尝试,但是他们不工作:

  reload(sys)
sys.setdefaultencoding('utf-8')

print os.popen('chcp 65001')。read()

sys.stdout.encoding ='cp65001'
pre>

也许你可以使用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()


解决方案

我知道你说你正在使用Python 2.6,但如果你能够使用Python 3.3,你会发现这是最终支持。



使用命令 chcp 65001



请参阅http://docs.python.org/dev/whatsnew/3.3.html#codecs


I'm using Python 2.6 on Windows 7

I borrowed some code from here: Python, Unicode, and the Windows console

My goal is to be able to display uft-8 strings in the windows console.

Apparantly in python 2.6, the

sys.setdefaultencoding()

is no longer supported

However, I wrote reload(sys) before I tried to use it and it magically didn't error.

This code will NOT error, but it shows funny characters instead of japanese text. I believe the problem is because I have not successfully changed the codepage of the windows console.

These are my attempts, but they don't work:

reload(sys)
sys.setdefaultencoding('utf-8')

print os.popen('chcp 65001').read()

sys.stdout.encoding = 'cp65001'

Perhaps you can use win32console to change the codepage? I tried the code from the website I linked, but it also errored from the win32console.. maybe that code is obsolete.

Here's my code, that doesn't error but prints funny characters:

#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()

解决方案

I know you state you're using Python 2.6, but if you're able to use Python 3.3 you'll find that this is finally supported.

Use the command chcp 65001 before starting Python.

See http://docs.python.org/dev/whatsnew/3.3.html#codecs

这篇关于如何在Windows控制台中显示utf-8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆