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

解决Python跨目录导入类时的ModuleNotFoundError问题

解决ModuleNotFoundError: No module named 'directoryA'的方法

你的问题本质是Python的模块搜索路径里找不到directoryA所在的目录——因为你从directoryB目录运行脚本时,当前工作目录是directoryB,而上一级的项目根目录不在搜索路径里。下面是几种实用的解决办法:

方法1:在脚本里手动添加项目根目录到搜索路径

在moduleB.py的最开头加入这段代码,把项目根目录(同时包含directoryA和directoryB的文件夹)添加到Python的模块搜索路径中:

import sys
from pathlib import Path

# 获取当前脚本的父目录的父目录,也就是项目根目录
root_dir = Path(__file__).parent.parent
sys.path.append(str(root_dir))

# 现在可以正常导入了
from directoryA.moduleA import MyClass

方法2:从项目根目录运行脚本

不要在directoryB目录下执行命令,回到包含directoryA和directoryB的根目录,执行:

python directoryB/moduleB.py

这种方式下,Python会把根目录加入搜索路径,自然能找到directoryA。

方法3:通过环境变量PYTHONPATH指定搜索路径

在终端里先设置PYTHONPATH为项目根目录的绝对路径,再运行脚本:

  • Windows(CMD):
set PYTHONPATH=C:\你的项目根目录绝对路径
cd directoryB
py moduleB.py
  • Linux/macOS:
export PYTHONPATH=/你的项目根目录绝对路径
cd directoryB
python moduleB.py

方法4:把项目变成可安装的包(适合长期维护的项目)

在项目根目录下创建pyproject.toml文件,内容示例:

[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"

[project]
name = "你的项目名"
version = "0.1.0"
packages = ["directoryA"]

然后在项目根目录执行:

pip install -e .

这会以开发模式安装你的包,之后不管在哪个目录运行脚本,都能直接导入directoryA里的模块。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 06:36:19