python改变默认编码

python改变默认编码_Harry‘s World!_百度空间

python改变默认编码

最近使用SyslogHandler处理日志的时候发现,基于socket的Handler都不能设置默认编码,比如SocketHandler, DatagramHandler和SyslogHandler。在这种情况下,对于unicode的日志会出现编码错误。

解决办法
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

为什么要reload(sys)呢?
Python的初始化脚本site.py会把sys模块的setdefaultencoding方法删除。
这是site.py中的代码及解释。
# Remove sys.setdefaultencoding() so that users cannot change the
# encoding after initialization.  The test for presence is needed when
# this module is run as a script, because this code is executed twice.
if hasattr(sys, "setdefaultencoding"):
del sys.setdefaultencoding

Python在初始化完毕之后,禁止用户改变默认编码,这有利于保持系统一致性。
sys.setdefaultencoding改变的是全局的默认编码,所以要注意对于其它python代码的影响。
原文地址:https://www.cnblogs.com/lexus/p/2757769.html