问题:
在Windows上编写好了py文件,到服务器上去运行时报错
在该段代码:email_txt=hunan+“今日油价:”+hunanoil+“元/升”+“\n”+news 报错
Traceback (most recent call last): File "/another/oil.py", line 152, in <module> UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)
解决:
import sys
defaultencoding = 'utf-8'
if sys.getdefaultencoding() != defaultencoding:
reload(sys)
sys.setdefaultencoding(defaultencoding)
原因:
我服务器上同时安装了python2和python3,可能导致字符编码等问题
Python在进行编码方式之间的转换时,会将 unicode 作为“中间编码”,但 unicode 最大只有 128 那么长,所以这里当尝试将 ascii 编码字符串转换成"中间编码" unicode 时由于超出了其范围,就报出了如上错误。