我有通过日志logging系统打印消息的脚本,或者有时会打印命令。 在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>
有没有一种通用的方法来使日志logging系统中的所有编码,打印命令等失效安全 (忽略错误)?
问题是,您的终端/外壳(cmd作为您在Windows上)不能打印每个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') ?
请参阅其他选项的文档 。
编辑如果你想为日志记录提供一个通用的解决方案,你可以StreamHandler
子类:
class CustomStreamHandler(logging.StreamHandler): def emit(self, record): record = record.encode('cp850', errors='replace') logging.StreamHandler.emit(self, record)