gpt4 book ai didi

python - 防止 Python 中的编码错误

转载 作者:太空狗 更新时间:2023-10-29 22:23:23 26 4
gpt4 key购买 nike

我有一些脚本可以通过日志系统打印出消息或者有时打印命令。在 Windows 控制台上,我收到如下错误消息

Traceback (most recent call last):
File "C:\Python32\lib\logging\__init__.py", line 939, in emit
stream.write(msg)
File "C:\Python32\lib\encodings\cp850.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_map)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u2019' in position 4537:character maps to <undefined>

是否有一种通用的方法可以使日志系统、打印命令等中的所有编码故障安全(忽略错误)?

最佳答案

问题是您的终端/shell(Windows 上的 cmd)无法打印每个 Unicode 字符。

您可以使用 str.encode 方法的 errors 参数对您的字符串进行故障安全编码。例如,您可以通过设置 errors='replace' 将不支持的字符替换为 ?

>>> s = u'\u2019'
>>> print s
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\encodings\cp850.py", line 12, in encode
return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can\'t encode character u'\u2019' in position
0: character maps to <undefined>
>>> print s.encode('cp850', errors='replace')
?

参见 documentation其他选项。

编辑 如果您想要一个通用的日志记录解决方案,您可以继承StreamHandler:

class CustomStreamHandler(logging.StreamHandler):

def emit(self, record):
record = record.encode('cp850', errors='replace')
logging.StreamHandler.emit(self, record)

关于python - 防止 Python 中的编码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11050292/

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