18.1 引言
当你编写了一个通用功能模块后,你可以将它打包并发布到 PyPI,供他人通过 pip install 使用。
本章将讲解:
- Python 模块与包的结构
- 使用 setuptools 构建安装包
- 发布到 PyPI
- 使用 venv 创建虚拟环境进行隔离测试
18.2 Python 包结构
18.2.1 基本目录结构
例如项目 mypkg:
mypkg/
├── mypkg/
│ ├── __init__.py
│ ├── core.py
│ └── utils.py
├── tests/
│ └── test_core.py
├── README.md
├── LICENSE
├── pyproject.toml
└── setup.cfg
- __init__.py:表明是一个 Python 包
- core.py、utils.py:模块文件
- tests/:单元测试
- pyproject.toml / setup.cfg:打包配置
18.3 创建包与配置文件
18.3.1 setup.cfg 示例
setup.cfg
[metadata]
name = mypkg
version = 0.1.0
author = Your Name
description = A sample Python package
long_description = file: README.md
long_description_content_type = text/markdown
license = MIT
url = https://github.com/yourname/mypkg
[options]
packages = find:
python_requires = >=3.8
include_package_data = True
install_requires =
requests
18.3.2 pyproject.toml 示例
pyproject.toml
[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"
pyproject.toml 是现代 Python 包的标准入口。
18.3.3 包内代码示例
mypkg/core.py
def greet(name: str) -> str:
return f"Hello, {name}!"
mypkg/init.py
from .core import greet
18.4 构建与发布
18.4.1 安装构建工具
pip install build twine
18.4.2 构建分发包
python -m build
✅ 将生成:
dist/
├── mypkg-0.1.0.tar.gz
└── mypkg-0.1.0-py3-none-any.whl
18.4.3 上传到 PyPI
- 注册 PyPI 账户:https://pypi.org/account/register/
- 使用 twine 上传:
twine upload dist/*
输入用户名和密码后,即可发布成功。
之后就能通过:
pip install mypkg
来安装使用你发布的包
18.5 使用虚拟环境(venv)
18.5.1 创建虚拟环境
python -m venv venv
18.5.2 激活虚拟环境
- Windows:
venvScriptsactivate
- macOS / Linux:
source venv/bin/activate
激活后可以安装依赖、测试你的包,不会污染全局环境。
18.5.3 退出虚拟环境
deactivate
18.6 小结
|
技术 |
用途 |
|
setuptools / build |
构建 Python 包 |
|
twine |
上传包到 PyPI |
|
venv |
创建隔离测试环境 |
✅ 掌握这章后,你就能把自己的 Python 模块打包成独立库,并发布给全世界使用。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
相关文章
暂无评论...

