在ubuntu 18.04 镜像容器中执行python程序报错:
ascii' codec can't encode characters in position 20-25: ordinal not in range(128)
查看python默认输出编码:
root@c02d090c172d:/# python3
Python 3.5.2 (default, Oct 8 2019, 13:06:37)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.stdout.encoding
'ANSI_X3.4-1968'
>>>
ANSI_X3.4-1968 是一种ASCII编码,而程序会输出中文,所以编码错误。
原因是docker镜像没有设置LANG环境变量,应该设置为中文字符集。
查看当前系统支持的字符集:
root@beb7f518401c:/mnt/log# locale -a
C
C.UTF-8
POSIX
root@beb7f518401c:/mnt/log#
可以选择C.UTF-8作为默认字符集,用以支持中文。
解决:
在dockerfile中设置环境变量:
ENV LANG C.UTF-8
这样做成的新镜像生成的容器的默认字符集就是C.UTF-8,支持中文编码。
root@c02d090c172d:/# python3
Python 3.5.2 (default, Oct 8 2019, 13:06:37)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.stdout.encoding
'utf-8'
>>>
注意:
不能使用系统中没有安装的其它中文字符集,比如zh_CN.UTF-8,即使更改了环境变量,还是无效。
本地主机系统,可以通过终端执行命令
export LANG=C.UTF-8 #临时生效
或者添加命令到 /etc/profile 配置文件,
source /etc/profile #永久生效
修改环境变量。
当前容器虽然也可以按照上面主机的方式,但是不能更新到其它新容器,所以根本的解决方式还是在做docker镜像时就配置好环境变量。
另:这里是用apt-get包安装的python,默认装了python3.5,而python3.7会强制使用UTF-8编码。
题外:
若 dockerfile文件里配置 RUN source /etc/profile是不生效的,docker会先跑起来一个容器,然后在容器里运行 source /etc/profile,之后把当前的容器 commit成新的镜像,但是运行期间的任何环境变量都不会生效,必须用 ENV来固化。—— 总结源自网络