How to fix: “UnicodeDecodeError: 'ascii' codec can't decode byte”

前端 未结 19 1540
谎友^
谎友^ 2020-11-22 01:21
as3:~/ngokevin-site# nano content/blog/20140114_test-chinese.mkd
as3:~/ngokevin-site# wok
Traceback (most recent call last):
File \"/usr/local/bin/wok\", line 4, in
         


        
19条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 02:10

    In a Django (1.9.10)/Python 2.7.5 project I have frequent UnicodeDecodeError exceptions; mainly when I try to feed unicode strings to logging. I made a helper function for arbitrary objects to basically format to 8-bit ascii strings and replacing any characters not in the table to '?'. I think it's not the best solution but since the default encoding is ascii (and i don't want to change it) it will do:

    def encode_for_logging(c, encoding='ascii'):
        if isinstance(c, basestring):
            return c.encode(encoding, 'replace')
        elif isinstance(c, Iterable):
            c_ = []
            for v in c:
                c_.append(encode_for_logging(v, encoding))
            return c_
        else:
            return encode_for_logging(unicode(c))
    
    `

提交回复
热议问题