【问题标题】:Python script in Docker can't find module in subdirectoryDocker中的Python脚本在子目录中找不到模块
【发布时间】:2022-07-21 19:29:09
【问题描述】:

我的项目结构如下:

.
├── my_script.Dockerfile
├── README.rst
├── log
│   └── my_script.log
├── pickles
├── requirements.txt
├── requirements_my_script.txt
├── src
│   ├── __init__.py
│   ├── __pycache__
│   ├── main.py
│   ├── modules
│   │   ├── __init__.py
│   │   └── module.py
│   ├── other_scripts
│   │   └── my_script.py
│   └── utils
│       ├── __init__.py
│       ├── __pycache__
│       └── logging_utils.py

my_script.Dockerfile如下:

# syntax=docker/dockerfile:1

FROM python:3.10-slim-buster
WORKDIR /src
COPY requirements_my_script.txt requirements_my_script.txt
RUN pip3 install -r requirements_my_script.txt
COPY src/. .
CMD ["python3", "other_scripts/my_script.py"]

my_script.py:

import logging

from src.utils.logging_utils import start_logger


def main(logger):
    # some code here
    logger.info('done')
    sleep(120)
       
    
if __name__=='__main__':
    logger = start_logger('my_script.log')
    try:
        logger.info('Starting..')
        main(logger)
    except Exception as e:
        logger.critical('Crashed with error: {}'.format(e))

还有 logging_utils.py:

import os
import logging

from logging.handlers import RotatingFileHandler

def start_logger(filename, level='INFO'): # INFO or DEBUG
    # # LOGGING
    log_folder = os.path.join(os.path.expanduser('~'), 'project_folder_name', 'log')
    if not os.path.exists(log_folder):
            os.makedirs(log_folder)
    log_filename = filename

    logger = logging.getLogger()
    logFormatter = logging.Formatter(fmt='%(asctime)s :: %(levelname)s - %(message)s')
    if level == 'DEBUG':
        logger.setLevel(logging.DEBUG)
    else:
        logger.setLevel(logging.INFO)

    # add a rotating handler
    handler = RotatingFileHandler(os.path.join(log_folder, log_filename), maxBytes=1000000, backupCount=1)
    handler.setFormatter(logFormatter)
    logger.addHandler(handler)
    return logger

这在我的机器上完美运行,但是当我构建 docker 并尝试运行它时,我收到以下错误:

from src.utils.logging_utils import start_logger
ModuleNotFoundError: No module named 'src'

我在 dockerfile 中尝试了几种不同的 COPY 语句,但均未成功。

谁能告诉我我做错了什么?

【问题讨论】:

  • 您在my_script.py 文件中尝试过from utils.logging_utils import start_logger 吗?
  • 在我的本地机器中已经失败:from utils.logging_utils import start_logger ModuleNotFoundError: No module named 'utils'
  • 我认为这是因为你在 DockerFile 中的WORKDIR。您应该更改它或复制 src 目录,因为您只复制 src 内容。不是那个目录
  • 将 dockerfile 更改为:``` FROM python:3.10-slim-buster WORKDIR /app COPY requirements_my_script.txt requirements_my_script.txt RUN pip3 install -r requirements_my_script.txt COPY src/ src/ CMD [" python3", "src/other_scripts/my_script.py"] ``` 但我得到同样的错误 (ModuleNotFoundError: No module named 'src')

标签: python docker python-module


【解决方案1】:

当您的代码执行其import

from src.utils.logging_utils ...

Python 查找./src/utils/logging_utils.py,相对于当前目录和 Python 搜索路径中的任何其他内容。但是在你的 Dockerfile 中,你去掉了 src 目录:

COPY src/. .

src 目录的内容复制到当前目录。我猜如果你docker run --rm your-image ls,你会立即在应用程序目录中看到utils 目录,而不是在src 子目录中。

如果需要将主机中的子目录复制到镜像中的子目录中,则需要在COPY两边重复目录名,如

COPY src/ src/

【讨论】:

    猜你喜欢
    • 2020-01-18
    • 2020-07-31
    • 2019-01-04
    • 2021-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    相关资源
    最近更新 更多