0

I have following piece of code:

with open("/media/file.txt", 'r', encoding='utf-8') as file:
    content = file.read()

When I run this code not from my IDE, but from Docker image, which I build like this:

RUN apt-get update && apt-get install -y --no-install-recommends \
    gcc \
    build-essential \
    zlib1g-dev \
    glade \
    python3-dev \
    python3-pip \
    python3-setuptools \
    pkg-config \
    libglib2.0-dev \
    libgirepository1.0-dev \
    libcairo2-dev \
    gir1.2-gtk-3.0 \
    && rm -rf /var/lib/apt/lists/*

RUN pip3 install wheel
RUN pip3 install pycairo
RUN pip3 install PyGObject
RUN pip3 install requests
RUN pip3 install pyinstaller

File which I'm trying to read contains UTF-8 chars. It is running OK via IDE and CMD of my PC, but fails with error:

'ascii' codec can't encode character '\xfc' in position 63: ordinal not in range(128)

When running via Docker image, which has Python 3.6 and above + Ubuntu 18.04

How could I solve this problem?

snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
Azii
  • 69
  • 1
  • 6
  • Does this answer your question? [UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)](https://stackoverflow.com/questions/9942594/unicodeencodeerror-ascii-codec-cant-encode-character-u-xa0-in-position-20) – PApostol Jul 05 '22 at 19:04
  • 2
    Reading a file is a *decode* error, not an encode error. Encoding is done when printing to the terminal, for example. Make a [mcve]. – Mark Tolonen Jul 05 '22 at 19:12
  • @Thanks for reply! No it doesnt, problem, I guess in Python versions or something similar. Since when I run encoding='ascii' on my PC it fails with the same error! – Azii Jul 05 '22 at 21:06
  • So make a [mcve]. Post exact code and full traceback of error message produced. – Mark Tolonen Jul 05 '22 at 22:23
  • @Azii: really trust us. It is not a problem of the `open` (which would cause a decode problem), but on a different place on the program (and very probably it is on `print`: your console is telling the program that it can understand only ASCII). You have many possibilities: fix the console, tell python that console is UTF-8 (so ignoring what console report), etc. – Giacomo Catenazzi Jul 06 '22 at 06:49
  • @snakecharmerb how can I vote up for your answer, it solved my problem! Thank you very much! – Azii Jul 06 '22 at 09:24
  • @GiacomoCatenazzi the problem was in ENV LANG of Docker image, thats why I was stuck so long, since I didnt understand why works on PC but doesnt from Docker image. Thank you for your time and effort! – Azii Jul 06 '22 at 09:25
  • @MarkTolonen problem was in Docker ENV LANG as snakecharmerb stated. Thank you for your time!! – Azii Jul 06 '22 at 09:26
  • @Azii you can upvote the answer on the Q&A that I linked if you found it helpful - that is where the credit lies. I will mark your question as a duplicate to help future searchers find the answer. – snakecharmerb Jul 06 '22 at 10:30

0 Answers0