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

如何用pyproject.toml/setup.cfg配置Python包依赖及解决TestPyPI安装问题

TestPyPI安装依赖找不到的解决方案与Python打包最佳实践

一、TestPyPI依赖找不到的核心原因

TestPyPI是独立的测试包索引,大部分常用包(如requests、pandas)要么未上传至该索引,要么仅存在旧版本/测试版本。默认情况下,pip仅从TestPyPI拉取资源时,自然会找不到这些依赖包。

二、解决依赖安装问题的具体方法

  • 方法1:安装时同时指定双源
    使用以下命令安装,让pip优先从TestPyPI拉取你的包,同时从官方PyPI获取依赖:

    pip install --index-url https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple/ your-package-name
    

    这是最实用的解决方案,无需额外上传依赖包。

  • 方法2:手动上传依赖至TestPyPI(不推荐)
    若需完全在TestPyPI环境内测试,需手动上传所有依赖(包括递归依赖),但工作量极大,仅适合极端场景。

三、基于setuptools的现代打包最佳实践

推荐采用pyproject.toml+setup.cfg的配置组合,精简甚至省略setup.py,符合PEP规范。

1. 配置文件分工

  • pyproject.toml:指定构建系统,告诉pip用setuptools构建包

    [build-system]
    requires = ["setuptools>=61.0"]
    build-backend = "setuptools.build_meta"
    
  • setup.cfg:存储所有元数据与依赖定义,示例如下:

    [metadata]
    name = your-package-name
    version = 0.1.0
    author = Your Name
    description = 带依赖的Python示例包
    long_description = file: README.md
    long_description_content_type = text/markdown
    url = https://your-project-url.com
    classifiers =
        Programming Language :: Python :: 3
        License :: OSI Approved :: MIT License
        Operating System :: OS Independent
    
    [options]
    packages = find:
    python_requires = >=3.8
    install_requires =
        requests>=2.25.1
        pandas>=1.3.0
        # 填写另外两个依赖
    
  • setup.py(可选):仅当需要动态版本或自定义构建逻辑时保留,否则可删除。若保留,内容如下:

    from setuptools import setup
    
    if __name__ == "__main__":
        setup()
    

2. 打包与上传流程

  • 安装构建工具:
    pip install build twine
    
  • 构建包(生成dist目录下的wheel和源码包):
    python -m build
    
  • 上传至TestPyPI:
    twine upload --repository testpypi dist/*
    
    执行后输入TestPyPI的账号密码即可。

3. 关键注意事项

  • 版本号需唯一:TestPyPI不允许重复上传同一版本,每次测试需更新版本号(如0.1.0→0.1.1)
  • 依赖版本范围合理:使用>=或~=(兼容更新)而非固定版本,减少冲突概率
  • 安装前清理缓存:执行pip cache purge避免旧缓存干扰测试结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 17:55:20