encoding - 如何在Python 2上更改stdin和stdout编码

标签 encoding stdout stdin python-2.x

我将Windows和Linux计算机用于同一项目。 Windows上stdin的默认编码为cp1252,而在Linux上为utf-8。

我想将所有内容更改为utf-8。
可能吗?我该怎么做?

这个问题是关于Python 2的。对于Python 3,请参见Python 3: How to specify stdin encoding

最佳答案

您可以通过在打印内容时不依赖隐式编码来实现。无论如何,不​​依赖它是一个好主意-隐式编码仅在打印到stdout以及将stdout连接到终端时才使用。

更好的方法是在各处使用unicode,并在各地使用codecs.opencodecs.getwriter。您将sys.stdout包装在一个对象中,该对象使用以下方式自动将Unicode字符串编码为UTF-8:

sys.stdout = codecs.getwriter('utf-8')(sys.stdout)

不过,这仅在您到处都使用unicode时才有效。因此,到处都使用unicode。真的,到处都是。

关于encoding - 如何在Python 2上更改stdin和stdout编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2737966/

相关文章:

json - 从 relfect.Value 编码 JSON

python - 如何使用 python 和 ffmpeg 库对视频进行转码(无命令行调用)

javascript - `$(' #form ').serialize()` 弄乱 UTF-8 字符

python - 使用 SSH 时仅在终止时显示 python 脚本的输出?

stdin - node.js:从标准输入读取同步?

json - 从 golang 中的标准输入读取 json 对象

c - 打印输出时如何保持stdin和stdout分开?

c# - 接收字符串作为内存流并进行编码后,将添加更多字符

Java:写入 Scala 输出流

ruby - 外部命令如何将其输出和退出状态返回给 Ruby?