如何更改 Python 2 上的 stdin 和 stdout 编码 [英] How to change the stdin and stdout encoding on Python 2

查看:29
本文介绍了如何更改 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:如何指定标准输入编码

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,请使用:

To read UTF-8 from stdin, use:

UTF8Reader = codecs.getreader('utf8')
sys.stdin = UTF8Reader(sys.stdin)

# Then, e.g.:
for _ in sys.stdin:
    print _.strip()

要将 UTF-8 写入 stdout,请使用:

To write UTF-8 to stdout, use:

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

# Then, e.g.:
print 'Anything'

这篇关于如何更改 Python 2 上的 stdin 和 stdout 编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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