Python同目录模块导入报错:调用函数触发ModuleNotFoundError
解决Python模块导入问题:ModuleNotFoundError: No module named 'mytest'
问题背景
文件结构如下:
-- main.py -- scripts/ -- __init__.py -- helper_functions.py -- mytest.py
各文件代码:
mytest.py
def test(): print("test")
helper_functions.py
import mytest def hello(): mytest.test() if __name__=="__main__": mytest.test()
scripts/init.py
from scripts.helper_functions import hello
main.py
from scripts import hello if __name__=="__main__": hello()
运行main.py时触发错误:
Traceback (most recent call last): File "\main.py", line 1, in <module> from scripts import hello File "\scripts\__init__.py", line 1, in <module> from scripts.helper_functions import hello File "\scripts\helper_functions.py", line 8, in <module> import mytest ModuleNotFoundError: No module named 'mytest'
解决方法
方法1:使用相对导入
在helper_functions.py中,把import mytest改成相对导入(因为mytest和helper_functions在同一目录下):
# helper_functions.py from . import mytest def hello(): mytest.test() if __name__=="__main__": mytest.test()
注意:相对导入仅适用于包内部,直接运行helper_functions.py会报错,需用python -m scripts.helper_functions命令运行该文件。
方法2:使用绝对导入
基于项目根目录的绝对导入,修改helper_functions.py的导入语句:
# helper_functions.py from scripts import mytest def hello(): mytest.test() if __name__=="__main__": mytest.test()
运行main.py时,项目根目录会自动加入Python模块搜索路径,因此不会出现导入问题。
方法3:临时扩展模块搜索路径
在helper_functions.py开头添加代码,将当前脚本所在目录加入Python的模块搜索路径:
# helper_functions.py import sys import os sys.path.append(os.path.dirname(os.path.abspath(__file__))) import mytest def hello(): mytest.test() if __name__=="__main__": mytest.test()
这种方式通过手动扩展路径,让Python能找到同目录下的mytest模块,适合临时场景。
内容的提问来源于stack exchange,提问作者alextc
相关产品推荐
相关产品推荐

