【问题标题】:Prevent encoding errors in Python防止 Python 中的编码错误
【发布时间】:2012-06-15 12:04:10
【问题描述】:

我有一些脚本可以通过日志系统打印出消息或有时打印命令。在 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>

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

【问题讨论】:

    标签: python windows encoding console


    【解决方案1】:

    问题是您的终端/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)
    

    【讨论】:

    • 但是如果我对所有字符串进行预编码,它们会改变类型(到字节),这可能会改变它们在内部的行为?它也在内置的编解码器库中。我无法改变这一点。我可以在编解码器中设置选项吗?
    • 使用通用日志记录解决方案编辑了我的答案。
    • 有没有通用的解决方案,这样我就不必在不同的地方更改代码(替代处理程序)?也许一些编码错误的全局选项?
    • 如果您不使用多个记录器(通过使用getLogger),您必须设置一次处理程序。如果您使用多个处理程序,您可以将setLoggerClass 与使用该处理程序的自定义类一起使用。
    • 这个answer 似乎很有效地完成了工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-07
    • 1970-01-01
    • 2015-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多