Python跨目录访问函数:优化main_program.py导入方式的方法
解决Python模块导入简化问题
你的目录结构如下:
Project.py | |--- sales_management | | | |--- data.py | |--- input2.py | |--- reports.py | |--- statics.py | |--- main_program.py
方案1:通过配置__init__.py实现批量导出
之前的ModuleNotFoundError大概率是因为__init__.py里的导入路径错误,或者未将函数暴露给模块命名空间。按以下方式修改sales_management/__init__.py:
# sales_management/__init__.py # 使用相对导入导出需要的函数 from .data import funct1, funct2 from .input2 import input_func1, input_func2 from .reports import report_gen1, report_gen2 from .statics import stat_calc1, stat_calc2
修改完成后,在main_program.py中只需少量代码即可导入所有需要的函数:
# main_program.py # 方式1:直接导入指定函数 from sales_management import funct1, input_func1, report_gen1 # 方式2:导入整个模块,通过模块别名调用 import sales_management as sm sm.funct2() sm.stat_calc1()
若仍报错,检查两个关键点:
- 运行
main_program.py时,当前工作目录必须是包含sales_management的父目录(即Project.py所在目录) - 确保模块/文件名未与Python内置模块重名
方案2:简化main_program.py中的导入语句
如果不想修改__init__.py,可以通过分组导入减少代码量:
# main_program.py # 按模块分组导入,每行对应一个模块的函数 from sales_management.data import funct1, funct2 from sales_management.input2 import input_func1, input_func2 from sales_management.reports import report_gen1, report_gen2 from sales_management.statics import stat_calc1, stat_calc2 # 或者用括号包裹实现紧凑写法 from sales_management.data import (funct1, funct2) from sales_management.input2 import (input_func1, input_func2) from sales_management.reports import (report_gen1, report_gen2) from sales_management.statics import (stat_calc1, stat_calc2)
对比两种方案,方案1更优——它将模块的对外接口统一在__init__.py中管理,后续函数增删或路径变动时,只需修改__init__.py,无需改动main_program.py的导入逻辑。
内容的提问来源于stack exchange,提问作者aki
相关产品推荐
相关产品推荐

