将Python CLI工具发布为pip模块的完整指南

将Python CLI工具发布为pip模块的完整指南

一、前期准备

  1. 注册PyPI账户

    • 访问PyPI官网注册账户
    • 推荐使用双因素认证增强安全性
  2. 生成API令牌

    • 访问PyPI账户管理
    • 生成具有"Upload packages"权限的令牌,妥善保存
  3. 确保模块名唯一性

    • PyPI搜索页面验证模块名未被使用
    • 建议使用小写字母和连字符的组合(如my-cli-tool

二、项目结构与配置

1. 基础项目结构
my-cli-tool/
├── src/
│   └── my_cli_tool/
│       ├── __init__.py
│       ├── cli.py          # 命令行入口
│       └── other_modules/
├── tests/
├── pyproject.toml
├── README.md
└── LICENSE
2. 配置文件详解

pyproject.toml(完整示例)

[build-system]
requires = ["hatchling>=1.10.0"]
build-backend = "hatchling.build"

[project]
name = "my-cli-tool"
version = "0.1.0"
authors = [
  { name = "Your Name", email = "you@example.com" },
]
description = "A powerful CLI tool for awesome tasks"
readme = "README.md"
license = { file = "LICENSE" }
requires-python = ">=3.8"
classifiers = [
    "Programming Language :: Python :: 3",
    "License :: OSI Approved :: MIT License",
    "Operating System :: OS Independent",
    "Topic :: Utilities",
    "Environment :: Console",
]
dependencies = [
    "click>=8.1.3",
    "requests>=2.28.2",
    "rich>=13.3.1",
]

[project.scripts]
my-cli = "my_cli_tool.cli:main"  # 命令行入口点

[project.urls]
"Homepage" = "https://github.com/yourusername/my-cli-tool"
"Bug Tracker" = "https://github.com/yourusername/my-cli-tool/issues"

setup.cfg(可选,用于补充元数据)

[metadata]
long_description_content_type = text/markdown

[options.entry_points]
console_scripts =
    my-cli = my_cli_tool.cli:main

三、构建与测试流程

1. 安装构建工具
python3 -m pip install --upgrade build twine
2. 构建分发包
python3 -m build
  • 生成文件位于dist/目录:
    • my-cli-tool-0.1.0-py3-none-any.whl(二进制分发包)
    • my-cli-tool-0.1.0.tar.gz(源代码分发包)
3. 测试上传到TestPyPI
# 上传到测试环境
python3 -m twine upload --repository testpypi dist/*

# 从TestPyPI安装(注意依赖处理)
pip install --index-url https://test.pypi.org/simple/ \
  --extra-index-url https://pypi.org/simple \
  my-cli-tool
4. 正式发布到PyPI
# 上传到生产环境
python3 -m twine upload dist/*

# 用户安装命令
pip install my-cli-tool

四、常见问题与解决方案

1. 依赖冲突处理

问题:TestPyPI缺少依赖包(如pyyaml
解决方案

pip install -i https://test.pypi.org/simple/ \
  --extra-index-url https://pypi.org/simple \
  my-cli-tool
2. 版本管理最佳实践
  • 使用语义化版本(SemVer):MAJOR.MINOR.PATCH
  • 通过hatch version命令自动更新版本:
    hatch version minor  # 升级次版本号
    
3. 持续集成(CI)自动发布

.github/workflows/publish.yml中配置:

name: Publish to PyPI

on:
  release:
    types: [created]

jobs:
  build-and-publish:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: '3.11'
      - run: python -m pip install build twine
      - run: python -m build
      - uses: pypa/gh-action-pypi-publish@release/v1
        with:
          user: __token__
          password: ${{ secrets.PYPI_API_TOKEN }}

五、进阶配置选项

1. 包含非Python文件

pyproject.toml中添加:

[tool.hatch.build]
include = [
    "src/my_cli_tool/data/*.json",
    "src/my_cli_tool/templates/*.txt",
]
2. 命令行入口优化

使用click库构建更友好的CLI:

# src/my_cli_tool/cli.py
import click

@click.group()
@click.version_option("0.1.0")
def main():
    """My powerful CLI tool"""
    pass

@main.command()
@click.argument("input_file")
@click.option("--output", "-o", help="Output file")
def process(input_file, output):
    """Process input file"""
    click.echo(f"Processing {input_file}...")
    # 业务逻辑

if __name__ == "__main__":
    main()
3. 创建可执行文件

使用pyinstaller打包:

pyinstaller --onefile --name my-cli src/my_cli_tool/cli.py

六、发布后维护

  1. 监控下载统计:通过PyPI Stats查看下载量
  2. 收集用户反馈:在GitHub Issues中管理
  3. 定期更新依赖:使用pip-toolspoetry管理依赖版本
  4. 文档维护:更新README和项目文档

完整示例代码可参考:GitHub - timerring/bilitool

更多细节请参考官方文档:Packaging Python Projects

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

timerring

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值