关于python中urllib.urlencode的时候出错:UnicodeEncodeError: ‘ascii’的记录

原文我参见了: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的Libsite-packages文件夹下新建一个sitecustomize.py,内容为:

  Python代码  

  1. # encoding=utf8  
  2. import sys  
  3.   
  4. reload(sys)  
  5. sys.setdefaultencoding('utf8')   

此时重启python解释器,执行sys.getdefaultencoding(),发现编码已经被设置为utf8的了,多次重启之后,效果相同,这是因为系统在python启动的时候,自行调用该文件,设置系统的默认编码,而不需要每次都手动的加上解决代码,属于一劳永逸的解决方法。

原文地址:https://www.cnblogs.com/God-Shell/p/3155902.html