在Python 3中在运行时更改stdin/stdout的编码

Pet*_*mit 4 unicode character-encoding python-3.x

在Python 3,stdin并且stdout是具有一个编码,因此吐出正常字符串(而不是字节)TextIOWrappers.

我可以使用环境变量PYTHONIOENCODING更改正在使用的编码.是否还有一种方法可以在我的脚本中更改它?

Mar*_*nen 5

实际上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')
?ÇÇ
Run Code Online (Sandbox Code Playgroud)

(我的终端不是UTF-8)

sys.stdout.buffer访问原始字节流.您还可以使用以下内容以stdout特定编码进行写入:

sys.stdout.buffer.write('\u5000'.encode('utf8'))
Run Code Online (Sandbox Code Playgroud)