记一次ubuntu因为无中文环境导致的报错

391 阅读1分钟

起因

项目是通过docker打包的ubuntu系统环境,因为需要添加新的python库,但是在docker构建镜像的过程中会报错如下

ERROR: Exception:
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/dist-packages/pip/_internal/cli/base_command.py", line 164, in exc_logging_wrapper
    status = run_func(*args)
  File "/usr/local/lib/python3.6/dist-packages/pip/_internal/cli/req_command.py", line 205, in wrapper
    return func(self, options, args)
  File "/usr/local/lib/python3.6/dist-packages/pip/_internal/commands/install.py", line 413, in run
    pycompile=options.compile,
  File "/usr/local/lib/python3.6/dist-packages/pip/_internal/req/__init__.py", line 81, in install_given_reqs
    pycompile=pycompile,
  File "/usr/local/lib/python3.6/dist-packages/pip/_internal/req/req_install.py", line 810, in install
    requested=self.user_supplied,
  File "/usr/local/lib/python3.6/dist-packages/pip/_internal/operations/install/wheel.py", line 737, in install_wheel
    requested=requested,
  File "/usr/local/lib/python3.6/dist-packages/pip/_internal/operations/install/wheel.py", line 589, in _install_wheel
    file.save()
  File "/usr/local/lib/python3.6/dist-packages/pip/_internal/operations/install/wheel.py", line 383, in save
    if os.path.exists(self.dest_path):
  File "/usr/lib/python3.6/genericpath.py", line 19, in exists
    os.stat(path)
UnicodeEncodeError: 'ascii' codec can't encode character '\u53f3' in position 81: ordinal not in range(128)

问题排查

因为本次镜像文件修改只是增加了python库相关的改动,通过查找报错内容查看相关博客,找到一篇文章内容是在ubuntu环境下通过python的print("中文")会发生报错,原因是python输出的是utf8编码格式,而ubuntu输出的编码格式不是utf8,所以最终python打印会报错,需要设置环境变量PYTHONIOENCODING=utf-8来改变输出的编码格式来解决,但是在设置了这个环境变量后,我的问题依然没有解决,继续查找相关博客,找到除了编码格式的原因外,还有一种可能是因为ubuntu系统中没有中文环境,所以导致在打印中文时会发生报错。

问题解决

在ubuntu下安装中文环境,dockerfile添加如下内容

RUN apt-get install -y locales locales-all language-pack-zh-hans
RUN locale-gen zh_CN.UTF-8 zh_CN && dpkg-reconfigure locales && dpkg-reconfigure locales && locale-gen zh_CN.UTF-8 && /usr/sbin/update-locale LANG=zh_CN.UTF-8
ENV LANG zh_CN.UTF-8
ENV LANGUAGE zh_CN:zh
ENV LC_ALL zh_CN.UTF-8

重新构建镜像,问题解决