PyPI 打包小记

你们这些家伙,好好看看我是怎么打包的吧!

GitHub 项目地址:hit-and-blow

一、文件结构介绍

打包前,需构建如下文件结构:

packaging_tutorial/
├── LICENSE
├── pyproject.toml
├── README.md
├── src/
│   └── YOUR_PACKAGE_NAME/
│       ├── __init__.py
│       └── example.py
└── tests/

各个 文件 / 文件夹 说明:

  • packaging_tutorial: 项目文件夹
  • LICENSE: 开源协议,可由 GitHub 生成
  • pyproject.toml: 打包配置文件
  • README.md: 项目文档
  • src: 项目结构要求的,用来放主程序
  • YOUR_PACKAGE_NAME: 主程序文件夹,以“你的包名”命名文件夹

二、添加配置文件

将以下内容修改一下,改改名字邮箱什么的,存成配置文件 pyproject.toml

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

[project]
name = "example_package_YOUR_USERNAME_HERE"
version = "0.0.1"
authors = [
  { name="Example Author", email="[email protected]" },
]
description = "A small example package"
readme = "README.md"
requires-python = ">=3.7"
classifiers = [
    "Programming Language :: Python :: 3",
    "License :: OSI Approved :: MIT License",
    "Operating System :: OS Independent",
]

[project.urls]
"Homepage" = "https://github.com/pypa/sampleproject"
"Bug Tracker" = "https://github.com/pypa/sampleproject/issues"

三、打包

3.1 准备打包环境

python3 -m pip install --upgrade pip
python3 -m pip install --upgrade build

3.2 打包

来到 pyproject.toml 所在目录,打开命令行,运行代码:

python3 -m build

操作后,当前目录下生成名为 dist 的文件夹。文件夹内是打包好的项目。

四、上传

4.1 准备上传环境

python3 -m pip install --upgrade twine

4.2 注册 PyPI 账号

PyPI 提供了测试服和正式服。测试上传选测试账号,正式上传选正式账号。

注册账号后申请 API token.

注册账号的链接 获取 API token 的链接
测试服 test.pypi.org/account/register test.pypi.org/manage/account
正式服 pypi.org/account/register pypi.org/manage/account

Note: 正式服需要完成 2FA 验证才能获取 API token,测试服无需验证

4.3 上传到 PyPI

两种情况:

1)上传测试服 TestPyPI

python3 -m twine upload --repository testpypi dist/*

2)上传正式服 PyPI

twine upload dist/* 

运行命令后,命令行会要求你输入 usernamepassword

  • username__token__
  • password 填你的 API token,就是 pypi- 开头那串东西

4.4 测试

现在可以用 pip install xxx 下载并测试了!

🖐️ 不要走开🖐️ 广告时间到!

作为练习,我为豆瓣 9.1 分的 《世界游戏大全51》 中的小游戏“猜颜色”写了解算器(作弊器)并打包上传到 PyPI。如果感兴趣,可以在 PyPIGitHub 下载~