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

标签 unicode character-encoding python-3.x

在 Python 3 中,stdinstdout 是具有编码的 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/

相关文章:

python - 使用Python和请求抓取网页时的字符集问题

c++ - 将 NSString 转换为 C 字符串时出错

python - Python xlsxwriter 库中的 UnicodeDecodeError

java - Java字符集-如何从System.in获得正确的输入?

python - 在 python 中初始化 lambda 函数列表

python - datetime.timestamp 在 pandas apply 和 dataframe 选择中返回不同的值

python - Django 对 ManyToManyField 中的成员集实现唯一约束

java - ™ 字符未被 GetStringChars() 正确翻译

jsf - 通过 PrimeFaces 输入组件检索的 Unicode 输入已损坏

asp.net - UTF-8 服务器编码会在 ASP.NET 站点上产生 � 字符