python3 UnicodeEncodeError: 'ascii' codec 问题

今天在部署一个服务的时候遇到一个问题,记录一下:

这个服务本身已经部署了多台机器,所以当出现下面的错误的时候感觉似乎又点儿不对。

报错:

UnicodeEncodeError: 'ascii' codec can't encode characters in position 36-41: ordinal not in range(128)

一看就是编码的问题,查询资料

https://segmentfault.com/q/1010000003932742

http://www.jianshu.com/p/9ed4cca9172e

https://www.binss.me/blog/solve-problem-of-python3-raise-unicodeencodeerror-when-print-utf8-string/

http://blog.csdn.net/fengfeiliusheng1990/article/details/77966396

以上的都没能解决问题,但是还是提供了思路

在服务器执行命令: locale charmap

输出:ANSI_X3.4-1968

这个字符集一旦出现中文就会报错。

主要报错的代码如下

def writeLog(message):

logDir =Cfg.PATH['log_dir']

if not os.path.exists(logDir):

os.makedirs(logDir)

msg ="[%s] %s" % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), message)

print(msg)

logger=logging.getLogger()

filename = time.strftime('%Y-%m-%d',time.localtime(time.time()))

handler=logging.FileHandler(os.path.join(logDir,filename + ".log"))

logger.addHandler(handler)

logger.setLevel(logging.ERROR)

logger.error(msg)

logger.removeHandler(handler)

然后看到这个:

1.http://blog.csdn.net/AckClinkz/article/details/78538462

PYTHONIOENCODING=utf-8 pythonyour_script.py

这样解决了控制台print输出中文字符的问题

2.第二个问题就是logging写文件的问题,按图索骥发现logging的FileHandler没有制定utf-8格式

果断修改代码

handler=logging.FileHandler(os.path.join(logDir,filename + ".log"),encoding='utf-8’)

经过这个问题,以后务必注意文件编码。只要有io以及控制台输入输出的都中文字符的都加上encoding

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容