You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python使用__init__.py导入带依赖子模块的报错问题

解决Python子模块导入依赖问题

问题根源

单独运行module_1/run_module.py时,Python会自动把当前脚本所在目录加入sys.path,因此直接import script_1能正常找到模块。但从上层run_everything.py导入子模块时,sys.path指向的是MyProject的上层目录,子模块内的旧导入方式无法定位到同目录下的脚本,导致ModuleNotFoundError。

解决方案

1. 修改子模块内部的导入方式

将module_1/run_module.py中的导入语句改为相对导入或绝对导入:

  • 相对导入(推荐,仅用于模块内部):
    # 导入整个模块
    from . import script_1, script_2
    # 或直接导入需要的函数
    from .script_1 import func_a
    from .script_2 import func_b
    
  • 绝对导入(适合跨模块调用):
    from module_1 import script_1, script_2
    # 或直接导入函数
    from module_1.script_1 import func_a
    from module_1.script_2 import func_b
    

2. 配置子模块的__init__.py

在module_1/__init__.py中添加语句,将run_module模块暴露给上层包:

from . import run_module

3. 上层脚本调用(符合你的期望)

在run_everything.py中直接按预期方式调用:

import module_1

module_1.run_module.start()

关键注意事项

  • 运行run_everything.py时,需在MyProject的上层目录执行命令,例如:
    python MyProject/run_everything.py
    
  • 若需在任意目录运行,可将MyProject所在目录添加到PYTHONPATH环境变量,确保Python能找到MyProject包。

你的三种尝试无效原因说明

  1. 仅在module_1/__init__.py导入script_1/script_2,但run_module.py内部的导入语句未修改,调用start()时仍会触发旧导入的错误;
  2. 空__init__.py配合点标记导入上层脚本,未解决run_module.py内部依赖的导入问题;
  3. from module_1.run_module import function()的导入方式本身没问题,但run_module.py内的依赖导入未修正,调用函数时仍会报错。

内容的提问来源于stack exchange,提问作者Chris M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 00:37:25