Encoding 如何在Python2上更改stdin和stdout编码

Encoding 如何在Python2上更改stdin和stdout编码,encoding,stdout,stdin,python-2.x,Encoding,Stdout,Stdin,Python 2.x,我正在为同一个项目使用Windows和Linux机器。Windows上stdin的默认编码为cp1252,Linux上为utf-8 我想把一切都改成utf-8。 可能吗?我怎么做 这个问题是关于Python 2的;对于Python3,请参见您可以通过在打印内容时不依赖隐式编码来实现这一点。在任何情况下,不依赖于此都是一个好主意——隐式编码仅在打印到stdout以及stdout连接到终端时使用 更好的方法是在任何地方使用unicode,并在任何地方使用codecs.open或codecs.getw

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

我想把一切都改成utf-8。 可能吗?我怎么做


这个问题是关于Python 2的;对于Python3,请参见

您可以通过在打印内容时不依赖隐式编码来实现这一点。在任何情况下,不依赖于此都是一个好主意——隐式编码仅在打印到stdout以及stdout连接到终端时使用

更好的方法是在任何地方使用
unicode
,并在任何地方使用
codecs.open
codecs.getwriter
。将
sys.stdout
包装到一个对象中,该对象自动将unicode字符串编码为UTF-8,例如:

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

不过,只有在所有地方都使用unicode时,这才有效。所以,在任何地方都要使用unicode。真的,到处都是。

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

要从
stdin
读取
UTF-8
,请使用:

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

# Then, e.g.:
for _ in sys.stdin:
    print _.strip()
UTF8Writer = codecs.getwriter('utf8')
sys.stdout = UTF8Writer(sys.stdout)

# Then, e.g.:
print 'Anything'
要将
UTF-8
写入
stdout
,请使用:

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

# Then, e.g.:
for _ in sys.stdin:
    print _.strip()
UTF8Writer = codecs.getwriter('utf8')
sys.stdout = UTF8Writer(sys.stdout)

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

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

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

有关不同平台上的编码检测和此变量的更多信息,请参阅文档。

我使用的一个简单代码片段,适用于我的ubuntu:python2.7和python3.6

从系统导入版本信息
如果version_info.major==2:#对于python2
导入编解码器
#标准时间
UTF8Reader=codecs.getreader('utf8')
sys.stdin=UTF8Reader(sys.stdin)
#用于stdout
UTF8Writer=codecs.getwriter('utf8')
sys.stdout=UTF8Writer(sys.stdout)
elif version_info.major==3:#用于python3
导入编解码器
#标准时间
UTF8Reader=codecs.getreader('utf8')
sys.stdin=UTF8Reader(sys.stdin.buffer)
#用于stdout
UTF8Writer=codecs.getwriter('utf8')
sys.stdout=UTF8Writer(sys.stdout.buffer)

stdin不是自动解码的,所以您必须自己进行解码。假设输入是UTF-8可能是个坏主意,但是如果你真的想的话,还有编解码器.getreader('UTF-8')(sys.stdin)。请注意,与Python 2不同,Python3实际上自动解码stdin:--这种行为可以按照文档中所述进行更改。在Python3中,是否有任何方法可以强制更改stdin的编码,而不考虑环境变量?在Python3.8中,编解码器。getreader('utf-8')(sys.stdin)不起作用。使用
codecs.getreader('utf-8')(sys.stdin.buffer)
codecs.getwriter('utf8')(sys.stdout.buffer)
代替。在Python 3.8中
codecs.getreader('utf-8')(sys.stdin)
(相当于本文)不起作用。使用
codecs.getreader('utf-8')(sys.stdin.buffer)
codecs.getwriter('utf8')(sys.stdout.buffer)