在Python 3中,stdin
and stdout
是具有编码的 TextIOWrappers,因此会输出普通字符串(而不是字节)。
我可以更改与环境变量一起使用的编码Python编码 http://docs.python.org/py3k/using/cmdline.html#envvar-PYTHONIOENCODING。还有一种方法可以在我的脚本本身中更改此设置吗?
实际上TextIOWrapper
does返回字节。它接受 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'))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)