最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - Files encoding changes after mounting to docker-container - Stack Overflow

programmeradmin3浏览0评论

The essence of the problem: when connecting via ssh to docker container with a Python environment, all files mounted in it are processed in ASCII encoding for some reason. The files themselves have the correct encoding. If they contain Unicode characters, the encoding error drops. By running the same code inside the container, everything is working normally. Host machine: Windows 11.

The project files and the error traceback:

  1. Dockerfile:
FROM python:3.6.9

RUN apt update && apt upgrade -y
RUN apt-get install -y openssh-server sudo
RUN mkdir /var/run/sshd

RUN useradd -m -d /home/docker_env -s /bin/bash docker_env &&  \
    echo 'docker_env:zak' | chpasswd && adduser docker_env sudo

RUN mkdir "app"
  1. docker-compose file:
services:
  ssh-test:
    build:
      context: ..
      dockerfile: ./docker_ssh/Dockerfile
    networks:
      zak_net:
        ipv4_address: 172.30.1.1
    ports:
      - "8000:8000"
      - "4444:22"
    volumes:
      - ${PROJECT_PATH}/configs:/opt/configs
      - ${PROJECT_PATH}/docker_ssh/start.sh:/start.sh
      - ${PROJECT_PATH}/test.py:/app/test.py
    tty: true
    command: "/bin/sh start.sh"

networks:
  zak_net:
    driver: bridge
    ipam:
      config:
        - subnet: 172.30.0.0/16
  1. start.sh file:
/usr/sbin/sshd -D
  1. test.py file:
import os

with open(os.getenv("CONF")) as f:
    print(f.read())
  1. Pycharm run-configuration: enter image description here

  2. Remote ssh Python interpreter: enter image description here

  3. Running test.py via Pycharm run configuration error traceback:

Traceback (most recent call last):
  File "/app/test.py", line 4, in <module>
    print(f.read())
  File "/usr/local/lib/python3.6/encodings/ascii.py", line 26, in decode
    return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 17: ordinal not in range(128)
  1. Running the same code inside docker-container:
>>> import os
>>> with open('/opt/configs/project.conf') as f:
...     print(f.read())
... 
[utf_test]
one = Один
two = Два
  1. Explicitly specifying the encoding in the open function is fixing problem, but it is not suitable as a solution to the problem.
  2. I have already tried changing locale settings; explicitly specifying the encodings in environment variables. It did not help.
发布评论

评论列表(0)

  1. 暂无评论