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

Python模块导入问题:如何调用引用子文件夹模块的模块?

Python模块导入问题解决方案

文件夹结构

root
  module_a
    hello.py
    submodule_a
      hi.py
  module_b
    howdy.py

各文件代码

hi.py

def myhi(hi):
    print("myhi " + hi)

hello.py

from submodule_a.hi import myhi

def myhello(hello):
    myhi("myhello " + hello)

howdy.py

from module_a.hello import myhello

def myhowdy(howdy):
    myhello("myhowdy " + howdy)

问题描述

运行howdy.py时最初无法找到module_a,添加sys.path.append(".")后,howdy.py能定位module_a,但hello.py又无法找到submodule_a。要求**完全不修改hello.py**解决该问题。

解决方案

方案1:修改howdy.py的路径配置 + 添加包标识文件

  1. 在module_a和submodule_a目录下各创建空的__init__.py文件,让Python将它们识别为可导入的包:
    root
      module_a
        __init__.py
        hello.py
        submodule_a
          __init__.py
          hi.py
      module_b
        howdy.py
    
  2. 修改howdy.py,将root目录和module_a目录加入Python的模块搜索路径:
    import sys
    from pathlib import Path
    
    # 获取root目录的绝对路径
    root_dir = Path(__file__).parent.parent
    # 获取module_a目录的绝对路径
    module_a_dir = root_dir / "module_a"
    
    # 加入搜索路径
    sys.path.append(str(root_dir))
    sys.path.append(str(module_a_dir))
    
    from module_a.hello import myhello
    
    def myhowdy(howdy):
        myhello("myhowdy " + howdy)
    
    此配置既保证howdy.py能找到module_a.hello,又让hello.py里的from submodule_a.hi import myhi能正确定位到submodule_a。

方案2:通过环境变量配置(无需修改代码)

  1. 同样在module_a和submodule_a下创建空__init__.py文件。
  2. 进入root目录,执行对应操作系统的命令:
    • Linux/macOS终端:
      export PYTHONPATH=$PYTHONPATH:./module_a
      python module_b/howdy.py
      
    • Windows PowerShell:
      $env:PYTHONPATH += ";.\module_a"
      python module_b/howdy.py
      
    该方法通过环境变量将module_a加入Python搜索路径,无需修改任何代码文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 13:35:17