Python3 UnicodeEncodeError 问题解决

用python3时,直接print('中文')出现下面的错误:
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)

对于上述问题,试了很多网上流传的各种版本解决方案,如:

import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )

但由于python3已经丢弃了setdefaultencoding("utf-8"),所以此路不通。下面介绍两种方法解决这个问题:

方法一:

加上下列代码,让python在标准输出的时候按utf-8编码输出

sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

方法二(推荐使用):

把print('中文') 改为 print(str('中文')),编译一下,中文友好地正常输出


阅读更多

Python3 CGI 中文问题 UnicodeEncodeError

09-01

首先不是python2,是python3rn其次python3中没unicode()这个东东!rnrn在CGI时的错误提示:rnTraceback (most recent call last): File "/usr/lib/cgi-bin/aa.py", line 29, in print(aaa) UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128) rnrn操作系统:Ubuntu 9.10 DesktoprnApache: 使用apt-get install apache2进行的安装rnPython: 源代码编译安装的python3.2rnrn源代码:aa.pyrn[code=Python]rn#!/usr/bin/python3rn# coding:utf-8rnrnprint("Content-type: text/html\r\n\r\n")rnprint("Environment")rnrnimport sysrnrnsys.stderr = sys.stdoutrnrnimport osrnrnos.environ["LANG"] = "en_US.UTF-8"rnrnrnprint(os.environ)rnrnprint(" ")rnprint(" ")rnprint(sys.getdefaultencoding())rnprint(" ")rnprint(" ")rnrnaaa = "中文"rnrnprint(aaa.encode('utf-8'))rnprint(" ")rnprint(" ")rnprint(aaa)rn[/code]rnrn在SHELL中执行的结果(使用print(aaa)能够正确的打印“中文”)rn[code=Python]rnaksai@aksai-laptop:/usr/lib/cgi-bin$ ./aa.py rnContent-type: text/htmlrnrnrnEnvironmentrnenviron('GDM_KEYBOARD_LAYOUT': 'us', 'GNOME_DESKTOP_SESSION_ID': 'this-is-deprecated', 'LESSOPEN': '| /usr/bin/lesspipe %s', 'QT_IM_MODULE': 'xim', 'LOGNAME': 'aksai', 'USER': 'aksai', 'HOME': '/home/aksai', 'PATH': '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games', 'DISPLAY': ':0.0', 'SSH_AGENT_PID': '2162', 'LANG': 'en_US.UTF-8', 'TERM': 'xterm', 'SHELL': '/bin/bash', 'XDG_SESSION_COOKIE': 'd0e2ff0a2bea80f62af6e9d44cb416fd-1314800273.494167-419471248', 'SESSION_MANAGER': 'local/aksai-laptop:@/tmp/.ICE-unix/2118,unix/aksai-laptop:/tmp/.ICE-unix/2118', 'SHLVL': '1', 'WINDOWID': '65011716', '_': './aa.py', 'XMODIFIERS': '@im=SCIM', 'USERNAME': 'aksai', 'COLORTERM': 'gnome-terminal', 'SSH_AUTH_SOCK': '/tmp/keyring-gXkTYH/socket.ssh', 'GNOME_KEYRING_SOCKET': '/tmp/keyring-gXkTYH/socket', 'GDMSESSION': 'gnome', 'DBUS_SESSION_BUS_ADDRESS': 'unix:abstract=/tmp/dbus-uwisuseGp7,guid=665f17044637987ab53184d34e5e4292', 'ORBIT_SOCKETDIR': '/tmp/orbit-aksai', 'GNOME_KEYRING_PID': '2103', 'GTK_IM_MODULE': 'scim-bridge', 'DESKTOP_SESSION': 'gnome', 'LESSCLOSE': '/usr/bin/lesspipe %s %s', 'GTK_MODULES': 'canberra-gtk-module', 'OLDPWD': '/usr/lib/cgi-bin/Trash', 'GDM_LANG': 'en_US.UTF-8', 'XAUTHORITY': '/var/run/gdm/auth-for-aksai-Fy9q8t/database', 'SPEECHD_PORT': '7560', 'XDG_DATA_DIRS': '/usr/share/gnome:/usr/local/share/:/usr/share/', 'PWD': '/usr/lib/cgi-bin', 'GTK_RC_FILES': '/etc/gtk/gtkrc:/home/aksai/.gtkrc-1.2-gnome2', 'LS_COLORS': 'rs=0:di=01;34:ln=01;36:hl=44;37:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31:*.taz=01;31:*.lzh=01;31:*.lzma=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.rar=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.axa=00;36:*.oga=00;36:*.spx=00;36:*.xspf=00;36:')rn rn rnutf-8rn rn rnb'\xe4\xb8\xad\xe6\x96\x87'rn rn rn中文rn[/code]rnrn在作CGI访问时的错误(访问地址:http://127.0.0.1/cgi-bin/aa.py)rn[code=Python]rnEnvironment environ('SERVER_SOFTWARE': 'Apache/2.2.12 (Ubuntu)', 'SCRIPT_NAME': '/cgi-bin/aa.py', 'SERVER_SIGNATURE': 'rnApache/2.2.12 (Ubuntu) Server at 127.0.0.1 Port 80rn\n', 'REQUEST_METHOD': 'GET', 'HTTP_KEEP_ALIVE': '115', 'SERVER_PROTOCOL': 'HTTP/1.1', 'QUERY_STRING': '', 'PATH': '/usr/local/bin:/usr/bin:/bin', 'LANG': 'en_US.UTF-8', 'HTTP_ACCEPT_CHARSET': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7', 'HTTP_USER_AGENT': 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.10) Gecko/20100915 Ubuntu/9.10 (karmic) Firefox/3.6.10', 'HTTP_CONNECTION': 'keep-alive', 'SERVER_NAME': '127.0.0.1', 'REMOTE_ADDR': '127.0.0.1', 'SERVER_PORT': '80', 'SERVER_ADDR': '127.0.0.1', 'DOCUMENT_ROOT': '/var/www', 'SCRIPT_FILENAME': '/usr/lib/cgi-bin/aa.py', 'SERVER_ADMIN': 'webmaster@localhost', 'HTTP_HOST': '127.0.0.1', 'REQUEST_URI': '/cgi-bin/aa.py', 'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'GATEWAY_INTERFACE': 'CGI/1.1', 'REMOTE_PORT': '45753', 'HTTP_ACCEPT_LANGUAGE': 'en-us,en;q=0.5', 'HTTP_ACCEPT_ENCODING': 'gzip,deflate')rnrnutf-8rnrnb'\xe4\xb8\xad\xe6\x96\x87' rnrnTraceback (most recent call last): File "/usr/lib/cgi-bin/aa.py", line 29, in print(aaa) UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128) rn[/code]rnrnApache环境配置(/etc/apache2/envvars):rn[code=Python]rn# envvars - default environment variables for apache2ctlrnrn# Since there is no sane way to get the parsed apache2 config in scripts, somern# settings are defined via environment variables and then used in apache2ctl,rn# /etc/init.d/apache2, /etc/logrotate.d/apache2, etc.rnexport APACHE_RUN_USER=www-datarnexport APACHE_RUN_GROUP=www-datarnexport APACHE_PID_FILE=/var/run/apache2.pidrnrn## The locale used by some modules like mod_davrn#export LANG=Crnexport LANG="en_US.UTF-8"rn## Uncomment the following line to use the system default locale instead:rn#. /etc/default/localernrnexport LANGrn[/code]rnrnApache的Deamon控制脚本(/etc/init.d/apache2)修改ENV变量如下:rn[code=Python]rn#ENV="env -i LANG=C PATH=/usr/local/bin:/usr/bin:/bin"rnENV="env -i LANG=en_US.UTF-8 PATH=/usr/local/bin:/usr/bin:/bin"rn[/code]rnrn传说中错误的原因是没有指定LANG,但不知道我修改Apache的配置是否正确。感谢各位赐教!

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