[英]Python - Writing Emoji characters to a log file
I am having difficulty writing emoji characters to a .log file.我无法将表情符号字符写入 .log 文件。 Here is the relevant snipet of my code:这是我的代码的相关片段:
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)
This is what is outputted into my console when message.content = 'hello there!这是当 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>
I have looked around and tried some solutions, but to no avail.我环顾四周并尝试了一些解决方案,但无济于事。 Is this error due to how my log file is encoded?这个错误是由于我的日志文件是如何编码的吗? If so, how can I change the encoding to allow utf-8 characters?如果是这样,我该如何更改编码以允许使用 utf-8 字符?
An allowable but not preferable solution would be a way to detect if these characters exist in the string so that I can instead not write the content to the log.一种允许但不优选的解决方案是一种检测字符串中是否存在这些字符的方法,这样我就可以不将内容写入日志。
This should fix your issue.这应该可以解决您的问题。 From: https://stackoverflow.com/a/43813727/6579239来自: 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.