我正在尝试在 Win 8 上使用 Python 2.7 创建一个 utf-8 日志文件。我总是收到 UnicodeDecodeError: 'ascii' codec can't Decode byte 0xfc inposition 20: ordinal not in range (128)
当我尝试记录其中包含非拉丁字符的 Windows 路径时。以下设置总是会抛出可怕的 UnicodeDecodeError
:
import logging
from logging import handlers
def GetLogger():
logger = logging.getLogger('log')
if not len(logger.handlers):
logger.setLevel(logging.DEBUG)
logger.propagate = False
# create a file handler
fileHandler = logging.handlers.TimedRotatingFileHandler('mylog.log', when = 'midnight', backupCount = 10, encoding = 'utf-8')
fileHandler.setLevel(logging.DEBUG)
# unicode template here
fileHandler.setFormatter(logging.Formatter(u'[%(levelname)-8s: %(asctime)s - %(filename)s:%(lineno)s - %(funcName)s()] - %(message)s'))
logger.addHandler(fileHandler)
return logger
logger = GetLogger()
path = 'e:\\\xcf\xf0\xee' + 'foo.bar' # actually I'm just calling os.getcwd() + 'foo.bar' here, and that's what it returns
print type(path) # prints <type 'str'>
logger.warning('Didn\'t find path %s' % path) # <- POOF!
# logger.warning('Didn\'t find path %s' % 'abcde') <- This would work
我尝试将 path
包装在 unicode(path)
中,但没有帮助。我已经无计可施了。如何记录这些棘手的路径?
最佳答案
调用os.getcwdu()
获取当前路径的Unicode版本,并在logger.warning
中使用Unicode字符串。
处理 Unicode 时,最好对所有文本使用 Unicode 字符串,或者使用 Python 3.x,它成为 'xxxx'
和 b'xxxx'< 的默认类型
是字节字符串的语法。您还可以使用from __future__ import unicode_literals
在 Python 2.7 中模仿 Python 3.x 的行为。请参阅PEP 3112了解更多信息。
关于python-2.7 - 在 Python 中将 str 消息插入 Unicode 日志模板时出现 UnicodeDecodeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41529114/