python3就没有编码问题了吗?

2020-05-13  本文已影响0人  金融测试民工

    python2中默认使用ascii,python3中默认使用utf-8,python3字符串的类型是str,且都是Unicode在内存中表示,为何会有编码问题呢

问题:

最近在获取版本平台发现后台有报错,代码一直未动,突然来一个编码错误,项目使用的是Python3,为何会报如下报错?

UnicodeEncodeError:'gb2312'codec can't encode character '\u2764'inposition15:illegal multibyte sequence

解决:

查了python3的系统编码,没问题

Python3.7.3(default, May 13 2020,16:43:18)

[GCC4.8.520150623(Red Hat4.8.5-36)]onlinux

Type"help","copyright","credits"or"license"formore information.

>>>importsys

>>>sys.getdefaultencoding()'utf-8'

系统编码无问题,输出的问题是不是输出的时候编码有问题,使用print使用了什么编码?

>>>importsys

>>>sys.stdout.encoding

'GB2312'

原来是操作系统使用GB2313编码无法识别

两种解决方法:

1、执行的时候使用

PYTHONIOENCODING=utf-8 python test.py

2、或者代码中加入以下申明

importcodecs

sys.stdout=codecs.getwriter("utf-8")(sys.stdout.detach())

上一篇下一篇

猜你喜欢

热点阅读