Python子目录文件导入报错:ImportError: No module named 'Lexer'求助
解决Python包内模块导入错误问题
你的目录结构如下:
Language/ Source/ __init__.py Main.py Lexer.py Parser.py Interpréter.py Shell.py
运行Shell.py时出现ImportError: No module named 'Lexer',但直接运行Main.py正常,核心原因是Python模块搜索路径的差异:
- 直接运行
Main.py时,脚本所在的Source/目录会被自动加入sys.path,所以from Lexer import Lexer能找到同目录的模块。 - 运行
Shell.py时,sys.path的根目录是Language/,此时Main.py作为Source包的一部分,它内部的from Lexer import Lexer会在Language/目录下查找Lexer.py,自然找不到目标文件。
解决方案一:使用相对导入(推荐)
修改Main.py中的导入语句,用相对路径指向同包内的模块:
# Main.py from .Lexer import Lexer from .Parser import Parser from .Interpréter import Interpréter
这种方式符合Python包的设计规范,能保证在包内任意位置导入时都能正确找到依赖模块。
如果需要直接运行Main.py,请在Language/目录下用模块方式启动:
python -m Source.Main
不要直接进入Source/目录运行python Main.py,否则会触发相对导入的脚本运行错误。
解决方案二:使用绝对导入
修改Main.py中的导入语句,基于Source包的绝对路径:
# Main.py from Source.Lexer import Lexer from Source.Parser import Parser from Source.Interpréter import Interpréter
这种方式不需要调整运行方式,但要求Language/目录在sys.path中(运行Shell.py时默认满足,因为Shell.py位于Language/下)。如果要直接运行Main.py,需要先将Language/目录加入环境变量:
# Linux/macOS export PYTHONPATH=/path/to/Language:$PYTHONPATH # Windows set PYTHONPATH=C:\path\to\Language;%PYTHONPATH%
之后再运行Main.py就不会报错。
额外优化:调整Shell.py的调用方式
你的Shell.py中导入Source.Main后,调用语法需要修正为:
# Shell.py # 方式一 import Source.Main Source.Main.run(some_code) # 方式二(更简洁) from Source import Main Main.run(some_code)
内容的提问来源于stack exchange,提问作者Paul Dannoot
相关产品推荐
相关产品推荐

