原文我参见了:http://hi.baidu.com/setcookie/item/ddc6b694b1f13435336eeb3c
为毛我要费事的写下了,就是为了让自己记录一下,下面的也是直接摘录过来的。
我的部分代码
def send_info(args):
try:
url = 'url'
args['uid'] = *****
args['pwd'] = 'e10adc3949ba59abbe56e0eeee57f20f883e'
j_data= urllib.urlencode(args) ==>python的默认编码是ascii码,所以在encode的时候就会出现异常
req = urllib2.Request(url, j_data)
response = urllib2.urlopen(req)
data = response.read()
json_data = json.loads(data)
print json_data
except Exception,e:
print 'send error:'
print e
方案是在python的Lib\site-packages文件夹下新建一个sitecustomize.py,内容为:
Python代码
- # encoding=utf8
- import sys
- reload(sys)
- sys.setdefaultencoding('utf8')
此时重启python解释器,执行sys.getdefaultencoding(),发现编码已经被设置为utf8的了,多次重启之后,效果相同,这是因为系统在python启动的时候,自行调用该文件,设置系统的默认编码,而不需要每次都手动的加上解决代码,属于一劳永逸的解决方法。
本文介绍了如何解决Python默认编码为ascii码导致的异常问题,并通过在sitecustomize.py中设置系统默认编码utf8来实现一劳永逸的解决方案。详细步骤包括:在Libsite-packages文件夹下新建sitecustomize.py文件,设置编码并重启Python解释器验证效果。
2330

被折叠的 条评论
为什么被折叠?



