问题描述
我正在使用Python 3.8。我有这样的目录结构:
├── package
│ ├── __init__.py
│ └── test2.py
└── test.py
test2的内容:
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 *
然后使用test2.py
中test.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 *
>
希望这可以为您提供帮助:)