【问题标题】:Python2 Logger "UnicodeDecodeError: 'ascii' codec can't decode" issuePython2 记录器“UnicodeDecodeError:‘ascii’编解码器无法解码”问题
【发布时间】:2019-01-02 23:23:57
【问题描述】:

我正在使用 Python2 编写,并导入了 __future__ 库。

当我想按如下方式记录一个 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)

【问题讨论】:

    标签: python-2.7 python-unicode


    【解决方案1】:

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

    #!/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("╔")
    

    【讨论】:

      猜你喜欢
      • 2011-09-26
      • 1970-01-01
      • 2015-11-06
      • 1970-01-01
      • 1970-01-01
      • 2013-08-20
      • 2014-04-09
      • 2018-08-02
      • 2013-09-23
      相关资源
      最近更新 更多