gpt4 book ai didi

Docker中的Python脚本在子目录中找不到模块

转载 作者:行者123 更新时间:2023-12-03 08:03:55 24 4
gpt4 key购买 nike

我的项目结构如下:

.
├── 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 语句,但没有成功。

有人可以告诉我我做错了什么吗?

编辑我也尝试了这个 dockerfile:

# syntax=docker/dockerfile:1

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"]

但我得到了完全相同的错误。

最佳答案

无需重构代码即可解决此问题的方法是在 dockerfile 中添加 ENV,如下所示:

# syntax=docker/dockerfile:1

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/
ENV PYTHONPATH /app
CMD ["python3", "src/other_scripts/my_script.py"]

关于Docker中的Python脚本在子目录中找不到模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73065072/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com