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

Python子目录脚本导入父目录模块失败的正确解决方法

问题说明

现有项目目录结构如下:

├── helper_files
│   ├── CONSTANTS.py
│   ├── bps.py
│   ├── bpsRestPy.py
│   └── helper.py
└── script_files
    ├── device_cleanup_script.py
    ├── device_sp_heavy_script.py
    ├── image_upload_script.py
    ├── profile_7_script.py
    ├── profile_9_script.py
    ├── shut_all_interfaces_script.py
    └── test.py

需要在script_files目录下的test.py中调用helper_files目录内的helper.py模块,使用如下代码导入时运行失败:

import sys
from pathlib import Path

path = str(Path(Path(__file__).parent.absolute()).parent.absolute())
sys.path.insert(0, path)

from helper_files import helper

helper.my_logger()
失败原因

helper_files目录缺少Python包标识文件,无法被Python解释器识别为可导入的包,因此导入语句会抛出模块找不到的错误。

正确实现方式
  • 首先在helper_files目录下新建一个空文件,命名为__init__.py,添加后该目录会被Python识别为合法的包目录,调整后的helper_files结构如下:
    ├── helper_files
    │   ├── __init__.py # 新增空文件即可,不需要写额外内容
    │   ├── CONSTANTS.py
    │   ├── bps.py
    │   ├── bpsRestPy.py
    │   └── helper.py
    
  • 调整test.py中的导入代码,原有路径计算逻辑可以简化,最终可正常运行的代码如下:
    import sys
    from pathlib import Path
    
    # 计算项目根目录(helper_files、script_files的共同父目录)
    project_root = Path(__file__).parent.parent.resolve()
    sys.path.insert(0, str(project_root))
    
    # 正常导入模块
    from helper_files import helper
    
    # 调用对应方法
    helper.my_logger()
    

注意:基于__file__动态计算项目根目录的写法兼容性更好,不会因为脚本运行时的工作目录变化出现路径错误。

内容的提问来源于stack exchange,提问作者Akshay J

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 07:12:26