Unicode 在Python3中在运行时更改stdin/stdout的编码

Unicode 在Python3中在运行时更改stdin/stdout的编码,unicode,character-encoding,python-3.x,Unicode,Character Encoding,Python 3.x,在Python3中,stdin和stdout是具有编码的TextIOWrapper,因此会输出普通字符串(而不是字节) 我可以更改与环境变量一起使用的编码。在我的脚本中是否也有办法改变这一点?我很确定这是不可能的。它在文档中明确指出,“如果在运行解释器之前设置了它,它将覆盖用于stdin/stdout/stderr的编码” 另外,我在尝试更改系统编码时出错,原因是: Traceback (most recent call last): File "<stdin>", line 1

在Python3中,
stdin
stdout
是具有编码的TextIOWrapper,因此会输出普通字符串(而不是字节)


我可以更改与环境变量一起使用的编码。在我的脚本中是否也有办法改变这一点?

我很确定这是不可能的。它在文档中明确指出,“如果在运行解释器之前设置了它,它将覆盖用于stdin/stdout/stderr的编码”

另外,我在尝试更改系统编码时出错,原因是:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: readonly attribute
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
AttributeError:只读属性
编辑:在Python2.x中,可以在脚本中更改stdin/out/err的编码。在Python3.x中,似乎必须使用
locale
(或者在运行脚本之前从命令行设置环境变量)


编辑:这可能会让您感兴趣

实际上
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:\dev\python32\lib\encodings\cp437.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')
倀

由于Python 3.7
TextIOWrapper
有一种方法可以更改流设置,包括编码:

sys.stdout.buffer.write('\u5000'.encode('utf8'))
sys.stdout.reconfigure(encoding='utf-8')
一个警告:只有在尚未开始读取的情况下,才能更改
sys.stdin
的编码