假设一个人不能使用print
(从而享受自动编码检测的好处)。因此,我们留下了sys.stdout
。但是,sys.stdout
与not do any sensible encoding是如此愚蠢。通过Python中的sys.stdout编写unicode字符串
现在一个读取Python的wiki页面PrintFails,去尝试一下下面的代码:
$ python -c 'import sys, codecs, locale; print str(sys.stdout.encoding); \
sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout);
但是这也不能正常工作(至少在Mac)。看到为什么:
>>> import locale
>>> locale.getpreferredencoding()
'mac-roman'
>>> sys.stdout.encoding
'UTF-8'
(UTF-8是什么人的终端了解)。
所以一个改变了上述的代码:
$ python -c 'import sys, codecs, locale; print str(sys.stdout.encoding); \
sys.stdout = codecs.getwriter(sys.stdout.encoding)(sys.stdout);
现在Unicode字符串被适当地发送到sys.stdout
,因此正确打印在终端上(sys.stdout
所连接的终端)。
这是在sys.stdout
中写入unicode字符串的正确方法还是我应该做其他事情?
编辑:有时候 - 比如,输出管道,以less
当 - sys.stdout.encoding
将None
。在这种情况下,上面的代码将失败。
S /我的/为了一致性 – icedwater 2014-07-11 06:14:28