首页 > 代码库 > python在windows下UnicodeDecodeError的解决方法
python在windows下UnicodeDecodeError的解决方法
之前在windows下使用python调用某些模块时都会报错,像这样:
C:\Documents and Settings\Administrator>python -m CGIHTTPServerTraceback (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 SimpleHTTPRequestHandler 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 can‘t decode byte 0xd7 in position 9: ordinalnot 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对齐,然后问题就解决了,详细原理等我深入了解了再补充过来
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。