Python导入同级目录包内模块时多种方式报错,如何正确实现导入
问题根因
你出现导入报错的核心原因是:直接运行findInfoSystem.py时,Python会将该脚本所在的crawler目录作为顶层工作目录,上层的dttn、项目根目录都不在Python的默认模块搜索路径中,且直接运行的脚本会被识别为__main__模块,不支持相对导入语法。
以下是两种无需修改sys.path的解决方案:
方案1:以模块形式运行脚本
不要直接执行python findInfoSystem.py,而是切换到dttn目录所在的项目根目录下,用-m参数将脚本作为模块运行:
python -m dttn.crawler.findInfoSystem
此时Python会自动将当前所在的项目根目录加入模块搜索路径,你在findInfoSystem.py中用如下导入语句即可正常调用:
from dttn.formatOutput.printChecked import print_checked_box
注意:如果你的项目根目录就是
dttn本身,没有上层的项目目录,那你需要切换到dttn目录下,运行python -m crawler.findInfoSystem,同时导入语句改为from formatOutput.printChecked import print_checked_box即可。
方案2:新增项目入口脚本
在dttn目录所在的项目根目录下新建入口文件main.py,统一作为项目启动入口,避免直接运行包内的业务脚本:
调整后的目录结构
项目根目录 ├── main.py └── dttn/ ├── __init__.py ├── formatOutput/ │ ├── __init__.py │ └── printChecked.py └── crawler/ ├── __init__.py └── findInfoSystem.py
main.py示例代码
from dttn.crawler.findInfoSystem import 你的业务主函数 if __name__ == "__main__": 你的业务主函数()
导入语句
findInfoSystem.py中还是使用如下导入语句即可:
from dttn.formatOutput.printChecked import print_checked_box
后续直接运行python main.py就能正常启动项目,无导入报错。
内容的提问来源于stack exchange,提问作者Thanh Tuấn Lê
相关产品推荐
相关产品推荐

