在Python 3中,stdin
和stdout
是具有编码的TextIOWrappers,因此会吐出普通字符串(不是字节)。
我可以更改与环境变量 PYTHONIOENCODING 一起使用的编码。有没有办法在我的脚本本身中更改它?
实际上TextIOWrapper
确实返回字节。 它采用 Unicode 字符串并返回特定编码的字节字符串。 若要更改sys.stdout
以在脚本中使用特定编码,下面是一个示例:
Python 3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print('u5000')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:devpython32libencodingscp437.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_map)[0]
UnicodeEncodeError: 'charmap' codec can't encode character 'u5000' in position 0: character maps to <undefined>>>> import io
>>> import io
>>> import sys
>>> sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8')
>>> print('u5000')
倀
(我的终端不是 UTF-8)
sys.stdout.buffer
访问原始字节流。 您还可以使用以下命令以特定编码写入stdout
:
sys.stdout.buffer.write('u5000'.encode('utf8'))
由于Python 3.7 TextIOWrapper
有一个可以更改流设置的reconfigure()
方法,包括编码:
sys.stdout.reconfigure(encoding='utf-8')
需要注意的是:只有在尚未开始读取sys.stdin
时,才能更改其编码。
确定这是不可能的。它在文档中明确指出"如果在运行解释器之前设置了此设置,它将覆盖用于 stdin/stdout/stderr 的编码"
尝试更改sys.__stdin__.encoding
时我也收到一个错误,说:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: readonly attribute
编辑:在python 2.x中,可以从脚本中更改stdin/out/err的编码。在python 3.x中,似乎您必须使用locale
(或在运行脚本之前从命令行设置环境变量)。
编辑:这可能很有趣,可以为您阅读 http://comments.gmane.org/gmane.comp.python.ideas/15313