I'm executing a python file inside a docker container, and need to import all the functions that I put into a separate python file called base_functions. However, writing from base_functions import * throws the error, that ModuleNotFoundError: No module named 'base_functions', even though base_functions.py is in the same directory as the main python file. How can I do this? Do I need to specify which python scripts I want to import beforehand, in the settings.ini or something?
This is the content of the Dockerfile:
FROM amancevice/pandas:0.24.1-alpine
RUN apk update
RUN apk add build-base
RUN apk add gcc musl-dev libc-dev util-linux-dev linux-headers python3-dev postgresql-libs postgresql-dev git libffi-dev libmemcached-dev zlib-dev \
ca-certificates zlib-dev jpeg-dev freetype-dev libpng
RUN pip3 install --upgrade pip
COPY requirements.txt .
RUN pip3 install -r requirements.txt
COPY src /vdp
WORKDIR /
ENTRYPOINT ["python3", "-m", "vdp"]
These are all the files in the directory of the project:
/home/cr/docker/71119/.
├── docker-compose.yaml
├── Dockerfile
├── Makefile
├── README.md
├── requirements.txt
├── settings.ini
└── src
├── base_functions.py
├── influx.py
├── __init__.py
└── __main__.py
解决方案
You're practically renaming your package (it smells like a package, having __init__.py and __main__.py) from "src" to "vdp" when you're creating the dockerfile.
I'd recommend:
Rename src/... to src/vdp/... (or vdp/...)
– at this point you should be able to run python -m vdp within the src directory on your host machine and things should work.
Change the Dockerfile stanzas to
COPY src /src
WORKDIR /src
ENTRYPOINT ["python3", "-m", "vdp"]
– this'd be equivalent to how you're running it on the host machine.
Another option would be to drop the /src in the repository and change things to COPY vdp /src/vdp.
The third option, of course, would be to set up proper Python packaging, have your setup.py build a proper wheel, then simply install that in the Docker container.