Python 3, is using sys.stdout.buffer.write() good style?

前端 未结 2 1459
礼貌的吻别
礼貌的吻别 2021-02-08 19:49

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.

I searched for writing unic

2条回答
  •  一个人的身影
    2021-02-08 20:32

    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.

    Edit: per comments, this isn't quite right -- @Miles gave the right variant (thanks!):

    sys.stdout = codecs.getwriter('utf8')(sys.stdout.buffer) 
    

    Edit: 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.

提交回复
热议问题