如何使用来自不同目录的 scripts/functions 编写 docker 文件 运行 一个 python 脚本

How to write a docker file running a python script using scripts/functions from different directory

我正在为来自 bitbucket 的 运行ning 一个 python 程序写一个 docker 脚本,比方说 myprogram.py。 python 程序使用其他目录中其他文件的特定函数,并像这样调用它们:

from mydirectory.myfunction import MyFunction

通常情况下,如果我只是克隆 bitbucket 存储库并 运行 它,不会发生错误。

我在 bitbucket 中的回购包括程序、一个 docker 文件和一些带有函数脚本的目录。所以我克隆了 repo,然后构建。

当我尝试构建它时,它成功了。我用这个命令构建它: docker build -t myprogram .

但是,当我使用命令时(-h 是用 argparse 制作的“帮助”选项,只是为了查看程序是否能够 运行 使用选项):

docker run --rm -it myprogram -h 它给了我错误:

Traceback (most recent call last):
File "/usr/src/myprogram.py", line 8, in <module>
  from mydirectory.myfunction import MyFunction
ImportError: No module named 'mydirectory' 

在 docker 文件中实现该程序使用 bitbucket 同一存储库中其他目录中其他脚本的函数的最佳方法是什么?我是 docker 的新手,如有任何帮助,我们将不胜感激!如果您需要任何其他信息,请告诉我。

我的 docker 文件如下所示:

FROM debian:stretch

ENV DEBIAN_FRONTEND noninteractive

RUN apt-get update -qq; \
    apt-get install -y -qq git \
    apt-utils \
    wget \
    python3-pip \
    ncbi-blast+ \
    libz-dev \
    ; \
    rm -rf /var/cache/apt/* /var/lib/apt/lists/*;

ENV DEBIAN_FRONTEND Teletype

# Install python dependencies
RUN pip3 install -U numpy

COPY myprogram.py /usr/src/myprogram.py

RUN mkdir /mydirectory

COPY mydirectory/* /mydirectory/

RUN chmod 755 /usr/src/myprogram.py; \

WORKDIR /workdir

# Execute program when running the container
ENTRYPOINT ["/usr/src/myprogram.py"]

问题是您正在将 mydirectory 复制到 / 而您的脚本位于 /usr/src。默认情况下,python 仅在 site-packages 目录和脚本所在的目录中查找包(当前工作目录用作备用,以防脚本位置不可用)。因此,您应该将 mydirectory 复制到与脚本相同的目录中(即 /usr/src)。因此,您有两种方法可以继续前进:

  1. mydirectory复制到/usr/src(您可以将其作为工作目录)。
  2. 在脚本中操纵 sys.path 以包含 mydirectory.
  3. 的绝对路径

为此,只需在导入之前将此代码段放入脚本中即可 mydirectory

import sys
sys.path.append('/')
del sys # If you don't need it anywhere else
from mydirectory.myfunction import MyFunction

您可能需要查看 sys.path 文档。