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

如何配置pyproject.toml使pip包中脚本可调用同目录下另一脚本

解决方案

1. 调整script.py代码

修改script.py,通过__file__获取当前脚本的绝对路径,拼接出同目录下tests.py的完整路径,彻底摆脱对当前工作目录的依赖:

import pytest
import os

def run():
    # 获取当前脚本所在的绝对目录
    script_dir = os.path.dirname(os.path.abspath(__file__))
    # 拼接tests.py的绝对路径
    tests_full_path = os.path.join(script_dir, "tests.py")
    
    # 执行整个测试脚本
    pytest.main([tests_full_path])
    
    # 执行后续业务逻辑
    print("I did something!")

2. 添加并配置pyproject.toml

在项目根目录(外层my-package/文件夹)创建pyproject.toml文件,配置项目元信息、依赖和命令行入口:

[project]
name = "my-package"
version = "0.1.0"
authors = [
  { name = "Your Name", email = "your.email@example.com" }
]
description = "Sample package that runs internal tests and executes custom logic"
requires-python = ">=3.8"
dependencies = [
  "pytest>=7.0.0"
]

# 配置命令行脚本,将run函数映射为可执行命令
[project.scripts]
my-package-run = "my-package.script:run"

3. 安装与验证

  1. 打开终端,进入外层my-package/目录(包含pyproject.toml的目录)
  2. 执行开发模式安装命令:
    pip install -e .
    
  3. 切换到任意其他目录,执行命令:
    my-package-run
    
    此时会自动定位到同目录下的tests.py并执行测试,随后输出I did something!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 09:07:35