如何在Python 2中更改标准输入和输出的编码

21

我在同一个项目中使用 Windows 和 Linux 机器。在 Windows 上,stdin 的默认编码是 cp1252,在 Linux 上则是 utf-8。

我希望把所有内容都改成 utf-8。这可行吗?我该如何做?

这个问题涉及 Python 2;有关 Python 3,请参见Python 3:如何指定 stdin 编码

4个回答

19

你可以通过不依赖于打印东西时的隐式编码来实现这一点。无论如何,不依赖隐式编码都是一个好主意--隐式编码只在将输出打印到标准输出且标准输出连接到终端时使用。

一个更好的方法是在任何地方都使用unicode,并且在任何地方都使用codecs.open或者codecs.getwriter。你可以将sys.stdout包装在一个对象中,该对象会自动将你的unicode字符串转换为UTF-8格式,例如:

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

只有当你在所有地方都使用Unicode时,才能使其起作用。因此,请在任何地方都使用Unicode。真的,任何地方。


3
stdin不会自动解码,因此您始终需要自己解码。假设输入是UTF-8可能是个坏主意,但如果您真的想要,可以使用codecs.getreader('utf-8')(sys.stdin) - Thomas Wouters
请注意,与Python 2相比,Python 3实际上会自动解码stdin:http://docs.python.org/3/library/sys.html#sys.stdin -- 此行为可以按照文档中的说明进行更改。 - Dr. Jan-Philip Gehrcke
1
在Python 3中,是否有一种方法可以强制更改STDIN的编码,而不考虑环境变量? - CMCDragonkai
在Python 3.8中,codecs.getreader('utf-8')(sys.stdin)不起作用。请改用codecs.getreader('utf-8')(sys.stdin.buffer)codecs.getwriter('utf8')(sys.stdout.buffer) - Eponymous

18

这是一个旧问题,但仅供参考。

要从标准输入读取 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 3.8中, codecs.getreader('utf-8')(sys.stdin)(相当于本帖子)不起作用。请使用 codecs.getreader('utf-8')(sys.stdin.buffer)codecs.getwriter('utf8')(sys.stdout.buffer) - Eponymous

10

Python会自动检测stdin的编码。当自动检测无法正常工作时,我发现最简单的指定编码的方法是使用 PYTHONIOENCODING 环境变量,例如以下示例:

pipeline | PYTHONIOENCODING="UTF-8" /path/to/your-script.py

如需了解有关不同平台上编码检测和此变量的更多信息,请查看sys.stdin文档。


0
一个我在Ubuntu上使用的简单代码片段,适用于Python2.7和Python3.6。
from sys import version_info
if version_info.major == 2:  # for python2
    import codecs
    # for stdin
    UTF8Reader = codecs.getreader('utf8')
    sys.stdin = UTF8Reader(sys.stdin)
    # for stdout
    UTF8Writer = codecs.getwriter('utf8')
    sys.stdout = UTF8Writer(sys.stdout)
elif version_info.major == 3:  # for python3
    import codecs
    # for stdin
    UTF8Reader = codecs.getreader('utf8')
    sys.stdin = UTF8Reader(sys.stdin.buffer)
    # for stdout
    UTF8Writer = codecs.getwriter('utf8')
    sys.stdout = UTF8Writer(sys.stdout.buffer)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接