在 Python 中通过 sys.stdout 编写 unicode 字符串 [英] Writing unicode strings via sys.stdout in Python

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

问题描述

假设一个人不能使用print(从而享受自动编码检测的好处).这样我们就剩下sys.stdout.然而,sys.stdout 非常愚蠢,以至于不做任何合理的编码.

现在阅读 Python wiki 页面 PrintFails 并尝试以下代码:

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

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

<预><代码>>>>导入语言环境>>>locale.getpreferredencoding()'宏指令'>>>sys.stdout.encoding'UTF-8'

(UTF-8 是终端所理解的).

于是把上面的代码改成:

$ python -c 'import sys, codecs, locale;打印 str(sys.stdout.encoding);sys.stdout = codecs.getwriter(sys.stdout.encoding)(sys.stdout);

现在 unicode 字符串正确发送到 sys.stdout 并因此正确打印在终端上(sys.stdout 附加到终端).

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

EDIT:有时——比如说,当将输出通过管道传送到 less 时——sys.stdout.encoding 将是 .在这种情况下,上面的代码将失败.

解决方案

我不清楚你为什么不能打印;但假设是这样,是的,这种方法在我看来是正确的.

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.

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);

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 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);

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

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

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 字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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