如何解决Python同包内模块导入引发的ModuleNotFoundError问题?
解决Python模块导入错误:ModuleNotFoundError: No module named 'func_b'
文件结构
main_dir/ ├─main.py └─utils/ ├─func_a.py ├─func_b.py └─__init__.py
各文件代码
main.py
from utils import func_a func_a.hello_world_n_times(5)
func_a.py
from func_b import hello_world def hello_world_n_times(n): for i in range(n): hello_world() if __name__ == '__main__': hello_world_n_times(5)
func_b.py
def hello_world(): print("Hello world!")
init.py
(文件内容为空)
运行报错
运行main.py时出现以下错误:
File "...\main_dir\utils\func_a.py", line 1, in <module> from func_b import hello_world ModuleNotFoundError: No module named 'func_b'
最佳解决方案
方法1:使用绝对导入(推荐)
修改func_a.py的导入语句,明确指定func_b所在的包路径:
from utils.func_b import hello_world def hello_world_n_times(n): for i in range(n): hello_world() if __name__ == '__main__': hello_world_n_times(5)
这种方式既支持从main.py导入运行,也支持在main_dir目录下直接执行python utils/func_a.py单独运行func_a.py,完全符合Python模块导入规范。
方法2:使用相对导入
如果不需要单独运行func_a.py,可以改用相对当前包的导入方式:
from .func_b import hello_world def hello_world_n_times(n): for i in range(n): hello_world() if __name__ == '__main__': hello_world_n_times(5)
注意:直接运行func_a.py时(比如执行python utils/func_a.py),这种相对导入会报错,因为此时func_a不是作为utils包的一部分被加载的。
错误原因说明
运行main.py时,Python会将main_dir目录加入模块搜索路径(sys.path)。func_a.py里原有的from func_b import语句会在sys.path中查找func_b,但func_b位于utils子目录下,不在sys.path范围内,因此触发模块找不到的错误。
内容的提问来源于stack exchange,提问作者Vinícius Almeida
相关产品推荐
相关产品推荐

