我正在尝试使用Python的日志包将UTF-8编码的字符串记录到文件中.作为玩具示例:
import logging
def logging_test():
handler = logging.FileHandler("/home/ted/logfile.txt", "w",
encoding = "UTF-8")
formatter = logging.Formatter("%(message)s")
handler.setFormatter(formatter)
root_logger = logging.getLogger()
root_logger.addHandler(handler)
root_logger.setLevel(logging.INFO)
# This is an o with a hat on it.
byte_string = '\xc3\xb4'
unicode_string = unicode("\xc3\xb4", "utf-8")
print "printed unicode object: %s" % unicode_string
# Explode
root_logger.info(unicode_string)
if __name__ == "__main__":
logging_test()
Run Code Online (Sandbox Code Playgroud)
这会在logging.info()调用中与UnicodeDecodeError一起爆炸.
在较低级别,Python的日志包使用编解码器包打开日志文件,传递"UTF-8"参数作为编码.这一切都很好,但它试图将字节字符串写入文件而不是unicode对象,这会爆炸.从本质上讲,Python正在这样做:
file_handler.write(unicode_string.encode("UTF-8"))
Run Code Online (Sandbox Code Playgroud)
什么时候应该这样做:
file_handler.write(unicode_string)
Run Code Online (Sandbox Code Playgroud)
这是Python中的一个错误,还是我正在服用疯狂的药丸?FWIW,这是一个库存Python 2.6安装.