Python 无法从包中导入模块

Python can't import module from package

我有一个具有以下布局的烧瓶 restful 项目(为方便起见更改了文件名)

myproject/
    __init__.py
    app.py
    common/
        __init__.py
        util.py
    foo/
        __init__.py
        main.py
        utilities.py

foo/ 只是一个文件夹,其中包含 API 端点之一的代码,我计划在将来添加其他端点,因此我有 common/util.py 文件包含我将与其他 API 端点一起使用的可重用函数。

foo/main.py

from flask_restful import Resource, request

from utilities import Analysis

class Foo(Resource):
    def get(self):      
        pass

foo/utilities.py 我有 类 方法获取一些数据,我将那些 类 导入到 foo/main.py 到 return JSON回应

foo/utilities.py 中的

类 也使用了 common/util.py 中的一些函数,但是当我尝试将某些内容从 common/util.py 导入到 foo/utilities.py 时,我得到 import common.util ModuleNotFoundError: No module named 'common'

这可能是什么原因造成的?我尝试导入各种方式: from common.util import my_func from .common.util import my_func from myproject.common.util import my_func

但 none 有效。

这是 myproject/app.py 以防万一:

from flask import Flask
from flask_restful import Api

from foo.main import Foo

app = Flask(__name__)
api = Api(app)

api.add_resource(Foo, '/Foo')

if __name__ == "__main__":
    app.run()

如果重要的话,我会在激活的 virtualenv 中完成所有这些工作

from common.util import my_func

在Python 3 这是绝对导入,即common/子目录的目录必须在sys.path。在你的情况下,这肯定是一种错误的方法。

from .common.util import my_func

此导入预期 commonfoo 的子目录,但事实并非如此。

from myproject.common.util import my_func

这最终是最好的方法,但要使其工作,myproject/ 子目录的父目录必须在 sys.path 中。安装整个 myproject 或将父目录添加到 $PYTHONPATH 环境变量或将目录添加到 foo/main.py 中的 sys.path。类似于:

PYTHONPATH=/home/to/parentdir /home/to/parentdir/myproject/foo/main.py

import sys
sys.path.insert(0, '/home/to/parentdir')

/home/to/parentdirmyproject/所在的目录。

安装 myproject 或将其父目录添加到 sys.path 后,您还可以使用相对导入。您需要记住 common 是与 foo 相比的兄弟包,因此导入必须不是来自 .common 而是来自 ..common:

from ..common.util import my_func