是否可以从 python 3.8 中的不同目录导入包中的所有模块?

Is it possible to import all modules within a package from a a different directory in python 3.8?

我正在使用 Python 3.8。我有这样的目录结构:

├── package
│   ├── __init__.py
│   └── test2.py
└── test.py

测试2的内容:

def x():
   print(999)

__init__.py 的内容:

from test2 import *

test.py 的内容:

import package
package.x()

运行 test.py 给出以下错误:

  from test2 import *
ModuleNotFoundError: No module named 'test2'

我希望 test.py 按预期工作。请帮忙。

正如@hjpotter92 所说,问题出在 __init__.py 文件中,因为输入应该是:

from .test2 import *

然后要在 test.py 中使用 test2.py 中的函数,您只需要这样的东西:

import package
package.x()

Here 您可以找到有关此主题的更多信息和一些建议。

编辑:

您必须使用 from .test2 import * 而不是 from test2 import * 导入的主要原因是因为 test2 在 Python 称为 package 的内容中(您称为同名目录)并且它应该在同一个包之外使用(在test.py中),否则你不需要使用.来导入它。

例如,如果您有这样的结构:

├── package
│   ├── __init__.py
│   └── test2.py
|   └── test3.py
└── test.py

test3.py中你可以这样做:from test2 import x因为在同一个package(命名包)

. 表示模块所在的包,例如,如果您想在 test.py 中导入而不使用 __init__.py,您应该这样做:from package.test2 import *

希望对您有所帮助:)