【问题标题】:Import error when running python script inside docker container?在 docker 容器中运行 python 脚本时导入错误?
【发布时间】:2019-08-25 07:17:27
【问题描述】:

我的目标是在容器内启动一个使用rabbitmq按摩的脚本,这里是重要的细节:

messenger.py,这是我要运行的脚本:

import pika
from . import create_app

class PikaMassenger():

    def __init__(self, *args, **kwargs):
        pass

    def consume(self, keys, callback):
        pass

    def __enter__(self):
        return self


    def __exit__(self, exc_type, exc_value, traceback):
        self.conn.close()



def start_consumer(app):

    def callback(ch, method, properties, body):
        try:
            print("Event recieved %r" % body)
            with app.app_context():
                pass

        except Exception as e:
            print("Consuming event %s failed: %s" % (method.routing_key, str(e)))

    with PikaMassenger() as consumer:
        consumer.consume(keys=['user.*', ], callback=callback)

if __name__ == "__main__":
    app = create_app()
    start_consumer(app)

我的__init__.py 只包含应用程序工厂(create_app)。我的 Dockerfile 和 docker-compose 是:

Dockerfile:

FROM  python:3.6

COPY requirements.txt /app/requirements.txt

WORKDIR /app

RUN pip install -r requirements.txt

COPY . /app

ENV SECRET_KEY dev


ENV FLASK_APP run.py

CMD  flask run

docker-compose.yaml:

  app:
    build:
      context: ./app
    expose:
      - "5000"
      - PYTHONUNBUFFERED=1
    restart: on-failure

  app_consumer:
    build:
      context: ./app
    command: python -m messenger.py
    environment:
      - PYTHONUNBUFFERED=1
    restart: on-failure
    depends_on:
      - rabbitmq 

所以我要做的是运行两个具有相同Dockerfile 的容器,同时覆盖其中一个中的command 参数,我知道鉴于上述细节,会发生错误:

 File "/app/massenger.py", line 2, in <module>
     from . import create_app
 ImportError: attempted relative import with no known parent package

也许我可能不得不更改docker-compose.yaml 中的工作目录,或者以不同的方式运行我的脚本。

如果需要更多详细信息,或者如果您想让我尝试一些东西,请告诉我。

【问题讨论】:

  • 无论 create_app 是什么,它都与 messenger.py 不在同一目录中。如果是通过 requirements.txt 安装的,直接导入即可。如果是你写的,那么你需要修复容器内脚本的路径。
  • 不,它在同一个目录下,它在 init.py.
  • from . import create_app 需要在__init.py__ 内定义此函数,或者在__init.py__ 内您需要类似于from .mymodule import create_app 的内容。是这样吗?
  • 确定它在 init.py 中,我想我在问题中已经明确了。

标签: python docker import docker-compose rabbitmq


【解决方案1】:

我认为这个错误的发生是因为'.'代表路径是错误的。在本地 '.'采用当前目录。但在 Docker '.'从某些根目录获取路径。

尝试将该路径作为静态路径或使用 os.getcwd() 方法。

【讨论】:

    猜你喜欢
    • 2022-01-13
    • 2019-03-18
    • 2020-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-04
    • 2021-09-16
    相关资源
    最近更新 更多