如何配置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. 安装与验证
- 打开终端,进入外层
my-package/目录(包含pyproject.toml的目录) - 执行开发模式安装命令:
pip install -e . - 切换到任意其他目录,执行命令:
此时会自动定位到同目录下的my-package-runtests.py并执行测试,随后输出I did something!
内容的提问来源于stack exchange,提问作者Johannes Wiesner
相关产品推荐
相关产品推荐

