python3设置编码,在Python 3中在运行时更改stdin / stdout的编码

In Python 3, stdin and stdout are TextIOWrappers that have an encoding and hence spit out normal strings (not bytes).

I can change the encoding that is being used with an environment variable PYTHONIOENCODING. Is there also a way to change this in my script itself?

解决方案

Actually TextIOWrapper does return bytes. It takes a Unicode string and returns a byte string in a particular encoding. To change sys.stdout to use a particular encoding in a script, here's an example:

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 "", line 1, in

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 >>> import io

>>> import io

>>> import sys

>>> sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8')

>>> print('\u5000')

倀

(my terminal isn't UTF-8)

sys.stdout.buffer accesses the raw byte stream. You can also use the following to write to stdout in a particular encoding:

sys.stdout.buffer.write('\u5000'.encode('utf8'))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值