python在windows下UnicodeDecodeError的解决方法

时间:2023-03-09 23:09:37
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 , in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "C:\Python27\lib\runpy.py", line , in _run_code
exec code in run_globals
File "C:\Python27\lib\CGIHTTPServer.py", line , in <module>
import SimpleHTTPServer
File "C:\Python27\lib\SimpleHTTPServer.py", line , in <module>
class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
File "C:\Python27\lib\SimpleHTTPServer.py", line , in SimpleHTTPRequestHand
ler
mimetypes.init() # try to read system mime.types
File "C:\Python27\lib\mimetypes.py", line , in init
db.read_windows_registry()
File "C:\Python27\lib\mimetypes.py", line , in read_windows_registry
for subkeyname in enum_types(hkcr):
File "C:\Python27\lib\mimetypes.py", line , in enum_types
ctype = ctype.encode(default_encoding) # omit in .x!
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd7 in position 9: ordinal
not in range()

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

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

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

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