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

同路径下存在product_library模块,运行behave仍报ModuleNotFoundError求助

ModuleNotFoundError: No module named 'product_library' 问题解决

我最近碰到一个特别费解的问题:明明项目里和测试代码同路径下就存在product_library模块,但用Behave跑测试时,一直抛出ModuleNotFoundError: No module named 'product_library'的错误,实在搞不懂哪里出问题了。

我的场景细节

  • 项目结构:product_library文件夹和存放测试代码的features文件夹处于同一根目录下,product_library里有initialize.py文件
  • 测试代码(在features/environment.py中):
from product_library.initialize import Initialize

def before_all(context):
    print(".............Executing before all.............\n")

def before_feature(context, feature):
    print(".............Executing before feature.............\n")
  • 运行命令:
behave -D BROWSER=chrome --no-capture

问题原因分析

其实核心原因是Python的模块查找路径问题:Behave运行时,默认只会把features文件夹的路径加入到Python的sys.path(模块查找路径)中,但不会自动添加项目根目录的路径。所以当你在environment.py里尝试导入上层目录的product_library时,Python找不到这个模块。

另外还要确认一个基础点:product_library必须是合法的Python包,也就是文件夹里必须存在__init__.py文件(可以是空文件,但不能少),否则Python不会把它识别为可导入的模块。

解决办法

办法1:手动在environment.py中添加根目录到sys.path

在environment.py的最顶部添加以下代码,把项目根目录路径加入到Python的模块查找路径中:

import sys
import os

# 获取environment.py所在文件夹的上级目录(也就是项目根目录)
root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(root_dir)

# 之后再导入模块就没问题了
from product_library.initialize import Initialize

def before_all(context):
    print(".............Executing before all.............\n")

def before_feature(context, feature):
    print(".............Executing before feature.............\n")

办法2:通过环境变量PYTHONPATH指定根目录

在运行Behave命令前,先把项目根目录添加到PYTHONPATH环境变量中:

  • Linux/macOS:
export PYTHONPATH=/你的项目根目录绝对路径:$PYTHONPATH
behave -D BROWSER=chrome --no-capture
  • Windows:
set PYTHONPATH=C:\你的项目根目录绝对路径;%PYTHONPATH%
behave -D BROWSER=chrome --no-capture

这样Python就能在运行时找到product_library模块了,测试应该就能正常执行啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 10:05:53