Python 包 : relative imports

标签 python python-module relative-import

我正在开发一个 Python 应用程序,该应用程序由一个核心和多个使用该核心的独立模块组成。我在设置包的相对导入时遇到困难。

app
  |- __init__.py
  |- core
        |- __init__.py
        |- corefile.py

  |- module1
        |- __init__.py
        |- main.py

__init__.py 文件是空的。我正在运行 Python 2.7.1。

main.py
from .core import *

运行 python main.py 导致 ValueError: Attempted relative import in non-package

类似问题:Ultimate answer to relative python imports , How to do relative imports in Python? , Relative imports in Python

感谢您的帮助。

最佳答案

简而言之,您只能使用本身已导入的包的相对导入。

例如,如果您有:

$ cat run.py
from app.module1 import main
main.main()
$ python run.py

然后你可以在 app/module1/main.py 中使用相对导入(尽管它需要是 from ..core import foo,因为 core/main.py 高一级。

关于Python 包 : relative imports,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10059002/

相关文章:

python - 如何在python中为shell命令使用变量值?

python - 当我在一个函数中声明多个连接时,如何确保连接关闭?

python - 导入错误 : No module named backend_tkagg

python - 如何将我的 Python C 模块放入包中?

python - 从父目录导入测试子目录而不使用打包,Python 2.7

python 3 : Relative import beyond toplevel

python - py2exe 的相对导入错误

python - Pandas :条件滚动计数

python - 类型错误 : 'DictWriter' object is not iterable

python - 如何使用相对导入将 python 脚本拆分为多个文件?