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

使用Pipenv创建Python包,pip安装时无法自动安装依赖?

问题描述

我正在创建一个Python包,使用Pipenv管理环境与依赖。希望他人通过pip或.whl文件安装该包时,能自动安装相关依赖。

我的Pipfile配置如下:

[[source]]
url = "https://pypi.org/simple"
verify_ssl = true
name = "pypi"

[packages]
numpy = "==1.26.4"
pandas = "==2.2.1"
pyproject-hooks = "==1.0.0"
python-dateutil = "==2.9.0.post0"
pytz = "==2024.1"
six = "==1.16.0"
tzdata = "==2024.1"
pytest = "*"

[dev-packages]
build = "==1.2.1"
packaging = "==24.0"
isort = "*"

[requires]
python_version = "3.11"

我的pyproject.toml文件配置如下:

[project]
name = "MyPyProject"
version = "0.0.1"
dynamic = ["dependencies"]

[tools.setuptools.dynamic]
dependencies = {file = ["requirements.txt"]}

[build-system]
requires = ["setuptools>=61","wheel"]

我已通过命令pipenv requirements > requirements.txt生成requirements.txt文件,但执行python -m build构建后,在全新环境中安装生成的.whl文件时,requirements.txt中的依赖并未被自动安装。请问我遗漏了什么关键步骤?


解决方法

核心问题出在requirements.txt的生成逻辑和构建资源的包含配置上,具体修正步骤如下:

1. 生成仅包含生产依赖的requirements.txt

pipenv requirements默认会同时导出生产和开发依赖,而你的包只需要生产依赖。执行以下命令重新生成:

pipenv requirements --without-dev > requirements.txt

2. 添加MANIFEST.in确保requirements.txt被打包

默认情况下,setuptools不会自动将requirements.txt纳入构建产物,导致安装时无法读取该文件。在项目根目录创建MANIFEST.in文件,内容为:

这会告诉构建工具将requirements.txt包含到包的元数据中。

3. 重新构建并验证

依次执行以下命令完成构建和测试:

# 重新生成正确的依赖文件
pipenv requirements --without-dev > requirements.txt
# 执行构建
python -m build
# 在全新环境安装测试
pip install dist/MyPyProject-0.0.1-py3-none-any.whl

可选优化:直接在pyproject.toml中定义依赖

如果你不想维护requirements.txt,也可以直接在pyproject.toml里明确列出生产依赖,这样更简洁且不易出错:

[project]
name = "MyPyProject"
version = "0.0.1"
dependencies = [
    "numpy==1.26.4",
    "pandas==2.2.1",
    "pyproject-hooks==1.0.0",
    "python-dateutil==2.9.0.post0",
    "pytz==2024.1",
    "six==1.16.0",
    "tzdata==2024.1"
]

[build-system]
requires = ["setuptools>=61","wheel"]

这种方式不需要额外维护requirements.txt和MANIFEST.in,更符合现代Python包的管理规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 04:36:09