如何在Python 2上更改stdin和stdout编码 [英] How to change the stdin and stdout encoding on Python 2
本文介绍了如何在Python 2上更改stdin和stdout编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我将Windows和Linux计算机用于同一项目。在Windows上,stdin的默认编码是cp1252,在Linux上,默认编码是utf-8。
I'm using Windows and Linux machines for the same project. The default encoding for stdin on Windows is cp1252, and on Linux it is utf-8.
我想将所有内容更改为utf-8。
有可能吗?我该怎么办?
I would like to change everything to utf-8. Is it possible? How can I do it?
这个问题是关于Python 2的。对于Python 3,请参见 Python 3:如何指定stdin编码
This question is about Python 2; for Python 3, see Python 3: How to specify stdin encoding
推荐答案
这是一个古老的问题,仅供参考。
This is an old question, but just for reference.
要从 stdin
读取 UTF-8
,请使用:
UTF8Reader = codecs.getreader('utf8')
sys.stdin = UTF8Reader(sys.stdin)
# Then, e.g.:
for _ in sys.stdin:
print _.strip()
写 UTF-8
到 stdout
,使用:
UTF8Writer = codecs.getwriter('utf8')
sys.stdout = UTF8Writer(sys.stdout)
# Then, e.g.:
print 'Anything'
这篇关于如何在Python 2上更改stdin和stdout编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文