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

Python跨目录导入问题:测试文件如何导入被测试文件函数?

问题描述

我已尝试将项目根目录添加到路径中,也参考过相关方法,但仍遇到导入问题。

我的项目结构如下:

package_name
- __init__.py
folder1
    - __init__.py
    - file_to_be_tested.py
    - tests
        - __init__.py
        - test_my_test.py

如何在test_my_test.py中导入file_to_be_tested.py里的函数?我已尝试以下两种方式:

from package.folder1.file_to_be_tested import my_func
from folder1.file_to_be_tested import my_func

我从package_name根目录下执行以下命令运行测试文件:

python folder1/tests/test_my_test.py

若我发帖前了解不足,在此致歉。

解决方案

方法1:相对导入+模块式运行

在test_my_test.py里用相对导入语法,测试文件和被测试文件同属folder1目录,直接向上回溯一级导入:

from ..file_to_be_tested import my_func

注意:这种方式不能直接用python folder1/tests/test_my_test.py运行,必须以模块方式启动,在package_name根目录下执行:

python -m folder1.tests.test_my_test

方法2:手动添加项目路径到Python环境

在test_my_test.py最开头加入这段代码,把项目根目录(package_name所在目录)添加到Python的搜索路径:

import sys
import os
# 向上回溯两级,定位到package_name目录
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../')))

from folder1.file_to_be_tested import my_func

修改后就能直接用你原来的命令python folder1/tests/test_my_test.py运行测试。

方法3:将项目安装为可编辑包

在package_name根目录下创建setup.py文件,内容如下:

from setuptools import setup, find_packages

setup(
    name="package_name",
    version="0.1",
    packages=find_packages()
)

然后在该目录下执行命令,把项目安装为可编辑版本:

pip install -e .

之后不管在哪运行测试,都能直接用绝对导入:

from folder1.file_to_be_tested import my_func

内容的提问来源于stack exchange,提问作者Prabhjot Singh Rai

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 08:32:15