python在windows下UnicodeDecodeError的解决方法

之前在windows下使用python调用某些模块时都会报错,像这样:

C:\Documents and Settings\Administrator>python -m CGIHTTPServer
Traceback (most recent call last):
  File "C:\Python27\lib\runpy.py", line 162, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "C:\Python27\lib\runpy.py", line 72, in _run_code
    exec code in run_globals
  File "C:\Python27\lib\CGIHTTPServer.py", line 30, in <module>
    import SimpleHTTPServer
  File "C:\Python27\lib\SimpleHTTPServer.py", line 27, in <module>
    class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
  File "C:\Python27\lib\SimpleHTTPServer.py", line 208, in SimpleHTTPRequestHand
ler
    mimetypes.init() # try to read system mime.types
  File "C:\Python27\lib\mimetypes.py", line 358, in init
    db.read_windows_registry()
  File "C:\Python27\lib\mimetypes.py", line 258, in read_windows_registry
    for subkeyname in enum_types(hkcr):
  File "C:\Python27\lib\mimetypes.py", line 249, in enum_types
    ctype = ctype.encode(default_encoding) # omit in 3.x!
UnicodeDecodeError: ascii codec cant decode byte 0xd7 in position 9: ordinal
not in range(128)

可以看到栈跟踪一直指向了python目录下的lib\mimetypes.py文件,根据查到的资料,解决方法是这样的

找到mimetypes.py文件第256行左右的default_encoding = sys.getdefaultencoding(),在它的前面加上

if sys.getdefaultencoding() != gbk: 
            reload(sys) 
            sys.setdefaultencoding(gbk)  

if和default_encoding对齐,然后问题就解决了,详细原理等我深入了解了再补充过来

python在windows下UnicodeDecodeError的解决方法,布布扣,bubuko.com

python在windows下UnicodeDecodeError的解决方法

上一篇:Python中的字符串处理


下一篇:C语言数据类型转换