python UnicodeEncodeError: 'ascii' codec can't encode characters 详解
新建一个test.py
#coding:utf-8
s='nihao中国'.decode('utf-8')
print type(s)
print s
执行错误:
Traceback (most recent call last):
<type 'unicode'>
File "/home/sdm/work/code/datadeal/tran_client/test_encode.py", line 5, in <module>
print s
UnicodeEncodeError: 'ascii' codec can't encode characters in position 5-6: ordinal not in range(128)
-------------
修改如下
#coding:utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
s='nihao中国'.decode('utf-8')
print type(s)
print s
---------一切正常-------
<type 'unicode'>
nihao中国
-------------------------
修改如下
#coding:utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
s='nihao中国'.decode('utf-8')
print type(s)
fn='/tmp/test.txt'
f=open(fn,'w')
f.write(s)
f.close()
print open(fn).read()
--------------
不报错
<type 'unicode'>
nihao中国
---------------------------------------
修改如下
#coding:utf-8
import sys
reload(sys)
#sys.setdefaultencoding('utf-8')
s='nihao中国'.decode('utf-8')
print type(s)
fn='/tmp/test.txt'
f=open(fn,'w')
f.write(s)
f.close()
print open(fn).read()
---------
报错
<type 'unicode'>
Traceback (most recent call last):
File "test_encode.py", line 11, in <module>
f.write(s)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 5-6: ordinal not in range(128)
-------------------------
说明 sys.setdefaultencoding
修改了默认的 unicode.encode 编码 行为
sys 为何reload 才有 sys.setdefaultencoding
-------
#coding:utf-8
import sys
#reload(sys)
sys.setdefaultencoding('utf-8')
-----------------
Traceback (most recent call last):
File "test_encode.py", line 4, in <module>
sys.setdefaultencoding('utf-8')
AttributeError: 'module' object has no attribute 'setdefaultencoding'
--------------------
grep -r -i 'setdefaultencoding' /usr/lib/python2.6
会看到
/usr/lib/python2.6/site.py: sys.setdefaultencoding(encoding) # Needs Python Unicode build !
/usr/lib/python2.6/site.py: # Remove sys.setdefaultencoding() so that users cannot change the
/usr/lib/python2.6/site.py: if hasattr(sys, "setdefaultencoding"):
/usr/lib/python2.6/site.py: del sys.setdefaultencoding
------------
site.py 里面
def main():
global ENABLE_USER_SITE
abs__file__()
known_paths = removeduppaths()
if ENABLE_USER_SITE is None:
ENABLE_USER_SITE = check_enableusersite()
known_paths = addusersitepackages(known_paths)
known_paths = addsitepackages(known_paths)
if sys.platform == 'os2emx':
setBEGINLIBPATH()
setquit()
setcopyright()
sethelper()
aliasmbcs()
setencoding()
execsitecustomize()
if ENABLE_USER_SITE:
execusercustomize()
# Remove sys.setdefaultencoding() so that users cannot change the
# encoding after initialization. The test for presence is needed when
# this module is run as a script, because this code is executed twice.
if hasattr(sys, "setdefaultencoding"):
del sys.setdefaultencoding
main()
这个地方把del sys.setdefaultencoding 防止用户在改变defaultencoding 不知道为什么
----------------------------------------
site 这个模块是自动加载的
验证下
python -c "import sys;print 'site' in sys.modules"
True
------------------
这个报错的
#coding:utf-8
import sys
s='nihao中国'.decode('utf-8')
print type(s)
fn='/tmp/test.txt'
f=open(fn,'w')
f.write(s)
f.close()
print open(fn).read()
-------
控制台直接运行 有时候不报错
#coding:utf-8
import sys
s='nihao中国'.decode('utf-8')
print type(s)
print s
但是 nohup 运行确报错:
nohup python test_encode.py
tail nohup.out
<type 'unicode'>
Traceback (most recent call last):
File "test_encode.py", line 5, in <module>
print s
UnicodeEncodeError: 'ascii' codec can't encode characters in position 5-6: ordinal not in range(128)
nohup 和 控制台运行 对python来说 标准输出是不一样的
-----------
在使用twisted.python.log 的时候和nohup 类似
代码前面加
import twisted.python.log as log
log.startLogging(sys.stdout)
之后 print unicode 仍然报错
#coding:utf-8
import sys
reload(sys)
#sys.setdefaultencoding('utf-8')
import twisted.python.log as log
log.startLogging(sys.stdout)
s='nihao中国'.decode('utf-8')
print type(s)
print s
2010-06-18 14:53:19+0800 [-] Log opened.
2010-06-18 14:53:19+0800 [-] <type 'unicode'>
2010-06-18 14:53:19+0800 [-] <unicode instance at 3074179752 with str error Traceback (most recent call last):
File "/usr/lib/python2.6/dist-packages/twisted/python/reflect.py", line 560, in safe_str
return str(o)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 5-6: ordinal not in range(128)
>
----
结论:
开文件开头加上 就比较安全了
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
----------
分享到:
相关推荐
主要介绍了Python UnicodeEncodeError: 'gbk' codec can't encode character 解决方法,需要的朋友可以参考下
使用Python写文件的时候,或者将网络数据流写入到本地文件的时候,大部分情况下会遇到:UnicodeEncodeError: ‘gbk’ codec can’t encode character ‘\xa0’ in position … 这个问题。 网络上有很多类似的文件...
UnicodeEncodeError: ‘ascii’ codec can’t encode characters in position 0-1: ordinal not in range(128) —————————- 经过网上搜索出错原因得到结果: python中如果使用系统默认的open方法打开的文件...
UnicodeEncodeError: ‘gbk’ codec can’t encode character ‘\u2022’ in position 7: illegal multibyte sequence Python中打开一个文件夹编写,file1 = open(‘E:\数据挖掘报告.txt’, ‘a’) 在写入的过程中...
UnicodeEncodeError: 'ascii' codec can't encode characters 这个错误是由于超链接中含有中文引起的,超链接默认是用ascii编码的,所以不能直接出现中文,若要出现中文, 解决方法如下: import urllib from ...
UnicodeEncodeError: ‘latin-1’ codec can’t encode characters in position 73-74: Body (‘测试’) is not valid Latin-1. Use body.encode(‘utf-8’) if you want to send it encoded in UTF-8. 解决: 对...
资源名称:ASCII表查询资料ASCII表查询文档,PDF版编程资料,本ASCII表查询手册列出了所有的A S C I I字符及其数值。有些A S C I I字符不能在计算机屏幕上显示出来,使用不同的字体可能会看到有些细微不同的结果。...
这是我积累的关于mysql的数据乱码的一写经验,有兴趣的可以看看
UnicodeEncodeError: ‘ascii' codec can't encode characters in position 24-25: ordinal not in range(128) 有趣的是,直接在 Python 环境下运行的时候,没有这样的错误。使用 uwsgi uwsgi.in
python 集成开发编码软件 1、先执行Python2.7.3.msi安装,安装...UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-2: ordinal not in range(128) Pysripter的解析器输出中文乱码解决方案:
大家好,我是庞老板咩,一名浙江大学动力工程20级推免生,最近开始自学Python。这是我的第一篇博客,很高兴可以在CSDN这个平台和大家分享交流^ ^ 首先,这是一段我初学爬虫时的代码: import urllib.request def ...
python2.78 32位 pyscripter2.53 32位 附带Pyscripter报错的解决方法: 第一次打开就出错:UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-2
'gbk' codec can't encode character '\U0001f370' in position 5: illegal multibyte sequence 去一看名字我懵逼了是个emoji???? 原来代码是这么写的 设置csv文件位UTF-8,代码改为 for i in b: persons = ...
UnicodeEncodeError: 'ascii' codec can't encode character u'\u258f' 查询资料后发现原因是pip安装python包会加载用户目录,用户目录恰好是中文的,ascii不能编码 打开对应的安装目录路径 D:\Python27\Lib\site-...
安装Ubuntu 在Windows下可以不用重新分区,直接像安装一个应用程序...否则会出现错误信息“UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)”而无法运行。
为什么会报错“UnicodeEncodeError: ‘ascii’ codec can’t encode characters in position 0-1: ordinal not in range(128)”?本文就来研究一下这个问题。 字符串在Python内部的表示是unicode编码,因此,在做...
UnicodeEncodeError: 'ascii' codec can't encode characters in position 10-11: ordinal not in range(128) 解决如下: import urllib.parse reqStr = '你好' encodeStr = urllib.parse.quote(reqStr) print...
UnicodeEncodeError: 'ascii' codec can't encode characters in position 69-78: ordinal not in range(128) 解决方法 单独处理url中的中文如: import urllib s=‘中文' s=urllib.parse.quote(s)\nurl='some ...
UnicodeEncodeError: ‘latin-1’ codec can’t encode characters in position; 找了一天终于搞明白了,默认情况下,mysql连接的编码是latin-1,你需要指定使用什么编码方式: connectionForURI(mysql://user:...