如何在 Dockerfile 中添加 PYTHONPATH 的路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49631146/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you add a path to PYTHONPATH in a Dockerfile
提问by arcoxia tom
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 completly new to docker.
如何在 Dockerfile 中添加 PYTHONPATH 的路径?那么当容器运行时它有正确的 PYTHONPATH 吗?我对 docker 完全陌生。
I've added ENV PYTHONPATH "${PYTONPATH}:/control"
to the Dockerfile as I want to add the directory /control
to PYTHONPATH
.
我已添加ENV PYTHONPATH "${PYTONPATH}:/control"
到 Dockerfile,因为我想将目录添加/control
到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.
当我使用 bash 访问容器docker exec -it trusting_spence bash
并打开 python 并运行目录下的命令时,该目录control
不在列表中。
import sys
print(sys.path)
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"]
回答by Erik Cederstrand
Just add an ENV
entry in your Dockerfile
:
只需ENV
在您的Dockerfile
:
ENV PYTHONPATH "${PYTHONPATH}:/your/custom/path"
Or set PYTHONPATH
in your startup script.
或者PYTHONPATH
在您的启动脚本中设置。
回答by Nimrod Morag
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.
您正确设置了 python 路径,但是您的命令不是由 shell 运行的,因此PYTHONPATH
不考虑环境变量。
chang your CMD
from "exec" form to "shell" form:
将您CMD
的“exec”形式更改为“shell”形式:
CMD python control/control_file/job.py
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.
注意:与 shell 形式不同,exec 形式不调用命令 shell。这意味着不会发生正常的 shell 处理。例如, CMD [ "echo", "$HOME" ] 不会对 $HOME 进行变量替换。如果你想要 shell 处理,那么要么使用 shell 形式,要么直接执行 shell,例如:CMD [ "sh", "-c", "echo $HOME" ]。当使用 exec 形式并直接执行 shell 时,就像 shell 形式一样,是 shell 进行环境变量扩展,而不是 docker。
回答by unlockme
Do it in a much simpler way. Add the python path in your .env file as a line in this way.
以更简单的方式进行。以这种方式将 .env 文件中的 python 路径添加为一行。
PYTHONPATH=/app/project_source/
PYTHONPATH=/app/project_source/