stdout编写unicode字符串

stdout编写unicode字符串

本文介绍了在Python中通过sys.stdout编写unicode字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

暂时假设不能使用print(因此可以享受自动编码检测的好处).这样就剩下sys.stdout了.但是,sys.stdout愚蠢到不进行任何明智的编码.

Assume for a moment that one cannot use print (and thus enjoy the benefit of automatic encoding detection). So that leaves us with sys.stdout. However, sys.stdout is so dumb as to not do any sensible encoding.

现在,人们阅读Python Wiki页面 PrintFails 并尝试以下代码:

Now one reads the Python wiki page PrintFails and goes to try out the following code:

$ python -c 'import sys, codecs, locale; print str(sys.stdout.encoding); \
  sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout);

但是,这也不起作用(至少在Mac上).太明白了为什么:

However this too does not work (at least on Mac). Too see why:

>>> import locale
>>> locale.getpreferredencoding()
'mac-roman'
>>> sys.stdout.encoding
'UTF-8'

(终端知道UTF-8).

(UTF-8 is what one's terminal understands).

因此,将以上代码更改为:

So one changes the above code to:

$ 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附加在终端上).

And now unicode strings are properly sent to sys.stdout and hence printed properly on the terminal (sys.stdout is attached the terminal).

这是在sys.stdout中编写unicode字符串的正确方法还是我应该做其他事情?

Is this the correct way to write unicode strings in sys.stdout or should I be doing something else?

编辑:有时-例如,将输出管道输送到less时-sys.stdout.encoding将是None.在这种情况下,上面的代码将失败.

EDIT: at times--say, when piping the output to less--sys.stdout.encoding will be None. in this case, the above code will fail.

推荐答案

我不清楚您为什么无法打印.但是假设是这样,对我来说,这种方法是正确的.

It's not clear to my why you wouldn't be able to do print; but assuming so, yes, the approach looks right to me.

这篇关于在Python中通过sys.stdout编写unicode字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 07:41