python2.7中的UnicodeDecodeError: 'ascii' codec can't decode byte 0xb0 in position 1: ordinal not in ra

本文介绍了一个在Python2.7环境下搭建HTTP服务器时遇到的UnicodeDecodeError错误及其解决办法。错误由mimetypes模块尝试读取注册表中的非ANSI字符引起。文章提供了一种通过修改默认编码来解决此问题的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在学习写一个简单的http服务器中报的错。


Traceback (most recent call last):
  File "httpservice.py", line 5, 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 0xb0 in position 1: ordinal not in range(128)

原因:

参考http://stackoverflow.com/questions/4237898/unicodedecodeerror-ascii-codec-cant-decode-byte-0xe0-in-position-0-ordinal

python27中的bug

This is a bug in mimetypes, triggered by bad data in the registry. (рєфшю/AMR is not at all a valid MIME media type.)

ctype is a registry key name returned by _winreg.EnumKey, which mimetypes is expecting to be a Unicode string, but it isn't. Unlike _winreg.QueryValueEx, EnumKey returns a byte string (direct from the ANSI version of the Windows API; _winreg in Python 2 doesn't use the Unicode interfaces even though it returns Unicode strings, so it'll never read non-ANSI characters correctly).

So the attempt to .encode it fails with a Unicode​Decode​Error trying to get a Unicode string before encoding it back to ASCII!


解决方法:

修改默认的编码方式

import sys
reload(sys)
sys.setdefaultencoding('gb18030')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值