Python 3是使用sys.stdout.buffer.write()好的样式吗? [英] Python 3, is using sys.stdout.buffer.write() good style?
问题描述
在我了解了阅读之后python 3.0 Web脚本中的unicode文件,现在是时候让我学习将 print()
与unicode一起使用了。
After I learned about reading unicode files in Python 3.0 web script, now it's time for me to learn using print()
with unicode.
我搜索了编写unicode的代码,例如此问题说明您不能将Unicode字符写入非Unicode控制台。但是,就我而言,输出是提供给Apache的,我确信它能够处理unicode文本。但是由于某种原因,我的网络脚本的 stdout
在 ascii
中。
I searched for writing unicode, for example this question explains that you can't write unicode characters to non-unicode console. However, in my case, the output is given to Apache and I am sure that it is capable of handling unicode text. For some reason, however, the stdout
of my web script is in ascii
.
很明显,如果我打开一个文件来写自己,我会做类似的事情
Obviously, if I was opening a file to write myself, I would do something like
open(filename, 'w', encoding='utf8')
但是因为提供了开放流,所以我不得不使用
but since I'm given an open stream, I resorted to using
sys.stdout.buffer.write(mytext.encode('utf-8'))
,似乎一切正常。这是否违反了良好行为规范或有任何意想不到的后果?
and everything seems to work. Does this violate some rule of good behavior or has any unintended consequences?
推荐答案
我认为您没有违反任何规则,但是
I don't think you're breaking any rule, but
sys.stdout = codecs.EncodedFile(sys.stdout, 'utf8')
看起来更方便/不太笨。
looks like it might be handier / less clunky.
编辑:根据评论,这不太正确-@Miles给出了正确的选择变体(谢谢!):
per comments, this isn't quite right -- @Miles gave the right variant (thanks!):
sys.stdout = codecs.getwriter('utf8')(sys.stdout.buffer)
编辑:如果可以安排环境变量 PYTHONIOENCODING
在Apache启动脚本时将其设置为utf8,那会更好,将 sys.stdout
设置为 utf8
自动;但是如果编解码器
解决方案不可行或不切实际。
if you can arrange for environment variable PYTHONIOENCODING
to be set to utf8 when Apache starts your script, that would be even better, making sys.stdout
be set to utf8
automatically; but if that's unfeasible or impractical the codecs
solution stands.
这篇关于Python 3是使用sys.stdout.buffer.write()好的样式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!