在 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:\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')
倀
(我的终端不是 UTF-8)
sys.stdout.buffer
访问原始字节流。您还可以使用以下命令以特定编码写入 stdout
:
sys.stdout.buffer.write('\u5000'.encode('utf8'))
关于unicode - 在 Python 3 中运行时更改 stdin/stdout 的编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12819099/