Python2 Logger "UnicodeDecodeError: 'ascii' codec can't decode" 问题



我正在导入__future__库的Python2中编写。

当我想记录一个unicode字符串如下,

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import logging
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.info("╔")

我犯了这个错误。

Traceback (most recent call last):
File "/usr/local/gcc-5-glibc-2.23/lib/python2.7/logging/__init__.py", line 876, in emit
stream.write(fs % msg.encode("UTF-8"))
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 231: ordinal not in range(128)

我有一个临时的丑陋修复。但是,为什么呢?还有更好的解决方案吗?

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import logging
import sys
reload(sys)  # noqa
sys.setdefaultencoding("utf8")
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.info("╔")

相关内容

最新更新