简体   繁体   English

Docker + Python3 UTF8 argv问题

[英]Docker + Python3 UTF8 argv problems

Consider the following Python program that prints its understanding of what command line arguments it got: 请考虑以下Python程序,该程序显示了对所获得的命令行参数的理解:

#!/usr/bin/env python3
print(repr(__import__("sys").argv))

Here's what happens when I run it with a Chinese character as an argument: 当我使用汉字作为参数运行它时,会发生以下情况:

$ /tmp/mytest 我                          
['/tmp/mytest', '我']

Now, consider the following Dockerfile that puts it in /tmp/mytest: 现在,考虑以下将其放在/ tmp / mytest中的Dockerfile:

FROM ubuntu:18.04
RUN apt-get update && apt-get install -y python3
RUN echo '#!/usr/bin/env python3' >> /tmp/mytest
RUN echo 'print(repr(__import__("sys").argv))' >> /tmp/mytest
RUN chmod +x /tmp/mytest

When I try to run it, the output differs: 当我尝试运行它时,输出有所不同:

$ sudo docker build -t mytest .                
Sending build context to Docker daemon  20.48kB
Step 1/5 : FROM ubuntu:18.04
 ---> 02f9d6707661
Step 2/5 : RUN apt-get update && apt-get install -y python3
 ---> Using cache
 ---> 5c9a6768a337
Step 3/5 : RUN echo '#!/usr/bin/env python3' >> /tmp/mytest
 ---> Using cache
 ---> e0410fc9684e
Step 4/5 : RUN echo 'print(repr(__import__("sys").argv))' >> /tmp/mytest
 ---> Using cache
 ---> d123c9645c5c
Step 5/5 : RUN chmod +x /tmp/mytest
 ---> Using cache
 ---> 9b2ac9b174e0
Successfully built 9b2ac9b174e0
Successfully tagged mytest:latest
$ sudo docker run -ti mytest /tmp/mytest 我
['/tmp/mytest', '\udce6\udc88\udc91']

Why is that? 这是为什么? Is Docker or Python to blame here? 是在这归咎于Docker还是Python? How do I make the script work the same way in both cases? 在这两种情况下,如何使脚本以相同的方式工作?

Apparently the problem goes away if you generate and export UTF8 locale, like in the following Dockerfile: 显然,如果您生成并导出UTF8语言环境,问题就消失了,例如以下Dockerfile中所示:

FROM ubuntu:18.04
RUN apt-get update && apt-get install -y python3 locales
RUN echo '#!/usr/bin/env python3' >> /tmp/mytest
RUN echo 'print(repr(__import__("sys").argv))' >> /tmp/mytest
RUN locale-gen en_US.UTF-8
ENV LC_ALL=en_US.UTF-8
RUN chmod +x /tmp/mytest

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM