Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

docker python custom module not found

I am new to docker and trying to move one simple application to docker. Python standard modules I am able to import using "pip install". However, I have some custom python utility files that I would like to use. These files are in separate package "utils".

In my main python file : test.py, I am doing

from utils import math.py, logger.py

This outside of docker works fine, but when running through docker gives me the error "ImportError: No module named utils".

My Dockerfile code:

FROM python:2.7.11
ADD ./ test_project/
WORKDIR test_project
ENV PATH=$PATH:/test_project/utils
ENV PYTHONPATH /test_project/utils

CMD [ "python", "report/test.py"]

My directory structure:

  • test_project
    • report
    • utils

Any suggestions?

like image 876
Dadu Avatar asked Jan 24 '17 00:01

Dadu


People also ask

Why can’t I Find my Python code in my Docker image?

It’s easy to mistakenly end up with multiple Python interpreters in your Docker image. When that happens, you might install your code with interpreter A, but try to run it with interpreter B—which then can’t find the code. Here’s a somewhat contrived example of how this happens:

What is/usr/local/bin/python in Docker?

/usr/local/bin/python is the Python interpreter provided by the Docker image. This is what the ENTRYPOINT is running. In /usr/bin/python3 is the Python interpreter installed via apt-get .

Why can't I import a module in Python?

The name of the module is incorrect The first reason of this error is the name of the module is incorrect, so you have to check out the module name that you had imported. For example, let's try to import os module with double s and see what will happen: as you can see, we got No module named 'oss'.

Why can’t I package my code with Docker?

Your code runs fine on your computer, but when you try to package it with Docker you keep getting ImportError s or ModuleNotFoundError: Python can’t find your code. There are multiple reasons why this can happen, some of them Python-specific, some of them Docker-specific.


1 Answers

You set PYTHONPATH to /test_project/utils. When trying resolve the module utils, it is looking for one of:

  • file /test_project/utils/utils.py
  • directory /test_project/utils/utils/ that contains __init__.py.

It looks like you have this?

utils/math.py
utils/logger.py

I wonder if what you really mean to do is

# different path...
ENV PYTHONPATH /test_project

from utils import math
from utils import logger
like image 90
Dan Lowe Avatar answered Sep 19 '22 17:09

Dan Lowe