Python 2.7:在Windows控制台中输出utf-8 [英] Python 2.7: output utf-8 in Windows console

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

问题描述

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

如果我尝试直接打印它,

If I try to print it directly,

>>> 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(否则它将无法理解我的输入).

So I change the console into UTF-8 from within Python (otherwise it won't understand my input).

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

然后输出编码为utf-8的字符串,因为Python不知道chcp 65001是UTF-8(已知的 bug ).

And then output the string encoded as utf-8, because Python doesn't know that chcp 65001 is UTF-8 (a known bug).

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

如您所见,它成功打印,直到碰到换行符,然后抛出IOError.

As you can see, it prints successfully until it hits a newline, then it throws an IOError.

以下解决方法有效:

def safe_print(str):
    try:
        print str.encode('utf-8')
    except:
        pass
    print

>>> safe_print(s)
testالله أكبر爆発ололо

但是必须有更好的方法.有什么建议吗?

But there must be a better way. Any suggestions?

推荐答案

在中搜索 python utf8 Windows 的第一个结果是问题使用控制台在Windows XP上获取要在UTF8中打印的python >描述了在Windows中从Python打印utf8的问题.

Searching SO for python utf8 windows brings as the first result the question Getting python to print in UTF8 on Windows XP with the console which describes what's the problem with printing utf8 in Windows from Python.

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

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