How do you add a path to PYTHONPATH in a Dockerfile

PythonDockerPath

Python Problem Overview


How do you add a path to PYTHONPATH in a Dockerfile? So that when the container is run it has the correct PYTHONPATH? I'm completely new to Docker.

I've added ENV PYTHONPATH "${PYTHONPATH}:/control" to the Dockerfile as I want to add the directory /control to PYTHONPATH.

When I access the container's bash with docker exec -it trusting_spence bash and open python and run the commands below the directory control is not on the list.

import sys print(sys.path)

FROM python:2
RUN pip install requests pymongo

RUN mkdir control

COPY control_file/ /control

ENV PYTHONPATH "${PYTHONPATH}:/control"

CMD	["python","control/control_file/job.py"] 

Python Solutions


Solution 1 - Python

Just add an ENV entry in your Dockerfile:

ENV PYTHONPATH "${PYTHONPATH}:/your/custom/path"

Or set PYTHONPATH in your startup script.

Solution 2 - Python

You're setting the python path correctly, but your command is not being run by a shell, so the environment variable PYTHONPATH is not considered.

chang your CMD from "exec" form to "shell" form:

CMD python control/control_file/job.py


From the Docs:

> Note: Unlike the shell form, the exec form does not invoke a command shell. This means that normal shell processing does not happen. For example, CMD [ "echo", "$HOME" ] will not do variable substitution on $HOME. If you want shell processing then either use the shell form or execute a shell directly, for example: CMD [ "sh", "-c", "echo $HOME" ]. When using the exec form and executing a shell directly, as in the case for the shell form, it is the shell that is doing the environment variable expansion, not docker.

Solution 3 - Python

Do it in a much simpler way. Add the python path in your .env file as a line in this way.

PYTHONPATH=/app/project_source/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionarcoxia tomView Question on Stackoverflow
Solution 1 - PythonErik CederstrandView Answer on Stackoverflow
Solution 2 - PythonNimrod MoragView Answer on Stackoverflow
Solution 3 - PythonunlockmeView Answer on Stackoverflow