现在,您可以阅读Python维基页面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
。在这种情况下,上述代码将失败。