Docker + Python3 UTF8 argv问题

时间:2018-04-25 11:45:01

标签: python python-3.x docker utf-8 command-line-arguments

考虑下面的Python程序,它打印出对它所获得的命令行参数的理解:

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

以下以中文字符作为参数运行时会发生什么:

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

现在,考虑将以下Dockerfile放入/ tmp / mytest:

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

当我尝试运行它时,输出不同:

$ 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']

为什么?在这里责怪Docker还是Python?在两种情况下如何使脚本以相同的方式工作?

1 个答案:

答案 0 :(得分:0)

如果您生成并导出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