我一直在尝试使用importlib
与 python3 (3.6)。
目录结构
main.py
#Note: I will only modify line 4 that uses importlib
import importlib
if __name__ == '__main__':
print("In main.py")
hello = importlib.import_module('hello', package='./')
print("Loaded hello.py")
hello.hello()
hello.py
def hello():
print('Hello world')
文件夹/hello.py
def hello():
print('Hello world in folder')
观察结果
If I do
hello = importlib.import_module('hello', package='./')
or
hello = importlib.import_module('hello')
它进口hello.py从根文件夹并打印hello world
.
If I do
hello = importlib.import_module('folder.hello')
它进口文件夹/hello.py从根文件夹并打印hello world in folder
.
但如果我这样做
hello = importlib.import_module('hello', package='folder')
or
hello = importlib.import_module('hello', package='./folder')
它给出了错误
Traceback (most recent call last):
File "main.py", line 4, in <module>
hello = importlib.import_module('hello', package='./folder')
File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'hello'
Problem
我不确定这里发生了什么。我很确定我对 python 模块和包的理解有问题。有人可以解释为什么这是预期的行为吗?