How do you add a path to PYTHONPATH in a Dockerfil

2020-08-09 05:22发布

问题:

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 containers 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\
&& pip install pymongo

RUN mkdir control

COPY control_file/ /control

ENV PYTHONPATH "${PYTONPATH}:/control"

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

回答1:

Just add an ENV entry in your Dockerfile:

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

Or set PYTHONPATH in your startup script.



回答2:

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.



回答3:

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/