【问题标题】:Python - Writing Emoji characters to a log filePython - 将表情符号字符写入日志文件
【发布时间】:2018-05-02 13:55:34
【问题描述】:

我在将表情符号字符写入 .log 文件时遇到了困难。这是我的代码的相关片段:

with open("testLog.log", "a") as myfile:
    print (message.content)                  #print to console - for debugging only
    print (message.content.encode('utf-8'))  #print to console - for debugging only
    myfile.write(message.content)

这是当 message.content = 'hello there! 时输出到我的控制台的内容????'

hello there! ????                              
b'hello there! \xf0\x9f\x91\x8d'
Ignoring exception in on_message
Traceback (most recent call last):
    File "C:\path\to\file\file.py", line 29, in on_message
    myfile.write(message.content)
    File "C:\Python\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
    UnicodeEncodeError: 'charmap' codec can't encode character '\U0001f44d' in position 13: character maps to <undefined>

我环顾四周并尝试了一些解决方案,但无济于事。这个错误是由于我的日志文件是如何编码的吗?如果是这样,我该如何更改编码以允许使用 utf-8 字符?

一个允许但不是优选的解决方案是检测这些字符是否存在于字符串中,这样我就可以不将内容写入日志。

【问题讨论】:

  • 您可以参考这个答案stackoverflow.com/a/32233385/4662041这可能会有所帮助。我只觉得你正在写入数据的文件的编码存在问题,如果它是utf-8,它不应该给出错误。

标签: python logging encoding emoji


【解决方案1】:

这应该可以解决您的问题。来自:https://stackoverflow.com/a/43813727/6579239

with open("testLog.log", "a") as myfile:
    print (message.content)                  #print to console - for debugging only
    print (message.content.encode('ascii', 'ignore').decode('ascii'))  #print to console - for debugging only
    myfile.write(message.content)

【讨论】:

    猜你喜欢
    • 2013-07-06
    • 2016-05-10
    • 1970-01-01
    • 2020-04-23
    • 1970-01-01
    • 2017-05-11
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    相关资源
    最近更新 更多