python 编码问题:'ascii' codec can't encode characters in position 的解决方案

报错:

'ascii' codec can't encode characters in position 8-50: ordinal not in range(128)

Python在安装时,默认的编码是ascii,当程序中出现非ascii编码时,python的处理常常会报这样的错UnicodeDecodeError: 'ascii' codec can't decode byte 0x?? in position 1: ordinal not in range(128),python没办法处理非ascii编码的,此时需要自己设置将python的默认编码,一般设置为utf8的编码格式。

查询系统默认编码可以在解释器中输入以下命令:

Python代码    
  1. >>>sys.getdefaultencoding()  

设置默认编码时使用:

Python代码    
  1. >>>sys.setdefaultencoding('utf8')  

 可能会报AttributeError: 'module' object has no attribute 'setdefaultencoding'的错误,执行reload(sys),在执行以上命令就可以顺利通过。

此时在执行sys.getdefaultencoding()就会发现编码已经被设置为utf8的了,但是在解释器里修改的编码只能保证当次有效,在重启解释器后,会发现,编码又被重置为默认的ascii了,那么有没有办法一次性修改程序或系统的默认编码呢。

 

有2种方法设置python的默认编码:

一个解决的方案在程序中加入以下代码:

Python代码    
  1. import sys  
  2. reload(sys)  
  3. sys.setdefaultencoding('utf8')   

 另一个方案是在python的Lib\site-packages文件夹下新建一个sitecustomize.py,内容为:

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

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

 

另外有一种解决方案是在程序中所有涉及到编码的地方,强制编码为utf8,即添加代码encode("utf8"),这种方法并不推荐使用,因为一旦少写一个地方,将会导致大量的错误报告,我曾经遇到这种情况,错误日志压缩之后尚有70多K,全都是这一个问题,让人有很崩溃的感觉。


展开阅读全文

'ascii' codec can't encode characters in position 0-10: ordinal not in range

10-09

我写了下面的代码,首次运行后提示“'ascii' codec can't encode characters in position 0-10: ordinal not in range”,然后在网上搜了一下此问题,就在文件的顶部加入“reload(sys) sys.setdefaultencoding( "utf-8" )”,但是点击F5运行程序就什么也出不来了。rnrn# -*- coding: cp936 -*- rnimport arcpy, os,sysrnrn__name__='publishHelper' rn rn# 将指定目录下所有的.mxd文档发布为地图服务 rn# folder:包含mxd文档的文件夹路径 rn# serviceDir:服务目录URL,例如http://localhost/arcgis/rest/services rn# serviceFolder:服务所在文件夹,如果为空,则表示根目录 rndef PublishAll(folder,serviceDir,serviceFolder): rn print "检查文件夹路径……" rn if os.path.isdir(folder) == False: rn print "输入的文件夹路径无效!" rn return rn print "遍历文件夹……" rn files = os.listdir(folder) rn for f in files: rn if f.endswith(".mxd"): rn mxdPath = os.path.join(folder, f) rn print "publishing: " + f rn PublishMxd(mxdPath, serviceDir, serviceFolder) rn else: rn continue rn#将mxd文档发布为服务:1.将mxd转为msd;2.分析msd;3.发布msd rndef PublishMxd(mxdPath, serviceDir, serviceFolder): rn #检查mxd和msd文件是否存在 rn print "检查文件路径……" rn if os.path.exists(mxdPath) == False: rn print "指定路径的mxd文档不存在!" rn return rn rn # 打开mxd文档 rn try: rn print "正在打开mxd文档……" rn mxd = arcpy.mapping.MapDocument(mxdPath) rn except Exception, e: rn print "open mxd error: ", e rn return rn else: rn print "mxd文档打开成功……" rn rn # 获取默认的数据框 rn print "正在读取mxd文档默认数据框……" rn df = "" rn try: rn frames = arcpy.mapping.ListDataFrames(mxd, "图层") rn if len(frames) == 0: rn frames = arcpy.mapping.ListDataFrames(mxd, "Layers") rn df = frames[0] rn except Exception, e: rn print "读取mxd文档默认数据框失败:", e rn return rn rn # 构造msd文档名称 rn msdPath = mxdPath.replace(".mxd", ".msd") rn # 将mxd转为msd rn print "正在将mxd文档转换为msd文档……" rn arcpy.mapping.ConvertToMSD(mxd, msdPath, df, "NORMAL", "NORMAL") rn rn # 分析msd rn print "正在分析文档……" rn analysis = arcpy.mapping.AnalyzeForMSD(mxd) rn # 列出分析结果信息 rn for key in ('messages', 'warnings', 'errors'): rn print "----" + key.upper() + "---" rn vars = analysis[key] rn for ((message, code), layerlist) in vars.iteritems(): rn print " ", message, " (CODE %i)" % code rn print " applies to:", rn for layer in layerlist: rn print layer.name, rn print rn rn #获取服务器信息 rn serviceName = os.path.basename(msdPath).replace(".msd", "") rn serverName = serviceDir.split("/")[2] rn try: rn #发布msd rn print "正在发布服务……" rn arcpy.mapping.PublishMSDToServer (msdPath, serviceDir, serverName, serviceName, serviceFolder, ["WMS", "KML"]) rn except Exception, e: rn print "发布服务失败:", e rn else: rn print "服务发布成功!" rnrnPublishAll("E:\\englishFileTwo", "http://localhost:6080/arcgis/rest/services", "dlwy") 论坛

python django :Exception Value: 'ascii' codec can't encode characters in positi

09-06

如果在models.py 里这样定义: rnrnmodels.py: rninfopic = models.FileField(upload_to='./pic/%Y/%m/%d/%H/', blank=True, null=True) rnrnfomrs.py: rninfopic = forms.FileField(label=u'相关图片', required=False) rnrnrnvimews.py: rnif form.is_valid(): rnnewinfo = Gqinfo( rntitle = form.cleaned_data['title'], rncontent = form.cleaned_data['content'], rninfopic = form.cleaned_data['infopic'], rnuser = request.user, rn) rnnewinfo.save() rnrnrnrn如果上传的图片里路径或图片的名字是中文的。比如: 中国.jpg 中国123.jpb rnrn在发布信息的时候就会出错。提示: rnrnrnrnrnrnEnvironment: rnrnrnRequest Method: POST rnRequest URL: http://www.aaa.com/post rnrnException Type: UnicodeEncodeError at /post/ rnException Value: 'ascii' codec can't encode characters in position 55-56: ordinal not in range(128) rnrnrnrnrnrnUnicodeEncodeError at /post/ rn'ascii' codec can't encode characters in position 55-56: ordinal not in range(128)Request Method: POST rnRequest URL: http://www.gq.com/post/ rnDjango Version: 1.5.2 rnException Type: UnicodeEncodeError rnException Value: 'ascii' codec can't encode characters in position 55-56: ordinal not in range(128) rnException Location: /usr/lib/python2.6/genericpath.py in exists, line 18 rnPython Executable: /usr/bin/python rnPython Version: 2.6.6 rnPython Path: ['/usr/lib/python26.zip', rn'/usr/lib/python2.6', rn'/usr/lib/python2.6/plat-linux2', rn'/usr/lib/python2.6/lib-tk', rn'/usr/lib/python2.6/lib-old', rn'/usr/lib/python2.6/lib-dynload', rn'/usr/lib/python2.6/site-packages', rnrnrnrnrnrnrn难道是那图片的路径不能是中文的吗? 论坛

没有更多推荐了,返回首页