起手式-解决Python在windows平台默认编码(encoding)为gbk所导致的open()函数报错及其他编码问题

大叔的python之路 andy 5年前 (2019-08-16) 7192次浏览 已收录 0个评论 扫描二维码

起手式-解决Python在windows平台默认编码(encoding)为gbk所导致的open()函数报错及其他编码问题

问题起源是在於使用 pyinstaller 打包文件时,发现某些第三方包里面使用 open()打开档案时没有指定编码(encoding)
这将导致我们所有打包的文件里面,如果有中文时就会出现错误。
在简体中文的window默认的编码为 gbk (繁体应该是 big5 吧?观迎吐槽),所以会出现在类似

UnicodeDecodeError: 'gbk' codec can't decode byte 0x91 in position 209: illegal multibyte sequence"

这样的错误

在官方文档说明 open() https://docs.python.org/3/library/functions.html#open
关键的一句话
if encoding is not specified the encoding used is platform dependent: locale.getpreferredencoding(False) is called to get the current locale encoding.
经过九九八十一天的翻查找,
https://docs.python.org/3/library/locale.html#locale.getdefaultlocale
再加上前人足迹,适合的解决方案很快就剩下更改默认的编码这个方式,
代码如下

import _locale 
_locale._getdefaultlocale = (lambda *args: ['en_US', 'utf8'])

运行时python解释器会取_getdefaultlocale()[1]作为默认编码,经过上方的重写后,会改变当前运行环境下的所有模块的默认编码。
windows平台下,open()函数会默认用utf-8编码打开文件,其实不止open()方法,跨模块、全局改变python解释器的默认编码为utf-8,会带来很多使用上的便利,而不需要被gbk编码报错的噩梦所纠缠。


神隊友學長Andy , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:起手式-解决Python在windows平台默认编码(encoding)为gbk所导致的open()函数报错及其他编码问题
喜欢 (4)
[[email protected]]
分享 (0)
andy
关于作者:
中年大叔,打拼 like young students.
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址