gpt4 book ai didi

python - 为什么相同的 utf-8 字符串在打印中正常,但在日志记录中却失败?

转载 作者:行者123 更新时间:2023-11-30 23:37:57 25 4
gpt4 key购买 nike

为了记录 utf-8 字符串,我需要手动做一些 print 为我做的事情吗?

for line in unicodecsv.reader(cfile, encoding="utf-8"):
for i in line:
print "process_clusters: From CSV: %s" % i
print "repr: %s" % repr(i)
log.debug("process_clusters: From CSV: %s", i)

无论字符串是基于拉丁语还是俄语西里尔语,我的打印语句都可以正常工作。

process_clusters: From CSV: escuchan
repr: u'escuchan'
process_clusters: From CSV: говоритъ
repr: u'\u0433\u043e\u0432\u043e\u0440\u0438\u0442\u044a'

但是,log.debug 不会让我传递相同的变量。我收到此错误:

Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/logging/__init__.py", line 765, in emit
self.stream.write(fs % msg.encode("UTF-8"))
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/codecs.py", line 686, in write
return self.writer.write(data)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/codecs.py", line 351, in write
data, consumed = self.encode(object, self.errors)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 28: ordinal not in range(128)

我的日志、格式化程序和处理程序是:

log = logging.getLogger(__name__)
loglvl = getattr(logging, loglevel.upper()) # convert text log level to numeric
log.setLevel(loglvl) # set log level
handler = logging.FileHandler('inflection_finder.log', 'w', 'utf-8')
handler.setFormatter(logging.Formatter('[%(levelname)s] %(message)s'))
log.addHandler(handler)

我使用的是 Python 2.6.7。

最佳答案

通过回溯读取,日志模块似乎在写入消息之前尝试对其进行编码。该消息被假定为 ASCII 字符串,但事实并非如此,因为它包含 UTF-8 字符。如果您在将消息传递给记录器之前将其转换为 Unicode,那么它可能会起作用。

    log.debug(u"process_clusters: From CSV: %s", i)

编辑,我注意到您的参数字符串已经解码为 Unicode,因此我相应地更新了示例。

此外,根据您的最新编辑,您可能希望在设置中使用 Unicode 字符串:

handler.setFormatter(logging.Formatter(u'[%(levelname)s] %(message)s'))
--^--

关于python - 为什么相同的 utf-8 字符串在打印中正常,但在日志记录中却失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14989487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com