打包自己的python代码为一个python包,并上传到pypi供自己和别人使用
本文介绍了如何从零开始创建并发布一个名为 aifund 的 Python 包到 PyPI。主要内容包括:准备工作(安装必要工具)、创建项目结构、编写核心代码与测试用例、配置元数据文件(pyproject.toml 和 setup.cfg)、构建打包、上传到 PyPI 的完整流程。最后提供了安装验证步骤和扩展建议(测试环境、自动化构建等)。整个过程清晰展示了 Python 包开发到发布的关键环节,适
·
假设你要创建一个可发布到 PyPI 的 Python 包(名叫 aifund),下面将从创建包结构 → 编写代码 → 构建 → 上传 → 安装验证。
🧩 一、准备工作
1. 环境要求
请确保安装了:
python --version # >= 3.8
pip install --upgrade pip setuptools wheel twine build
这几个库是发布包所必需的。
📁 二、创建项目结构
在你的工作目录下,创建如下文件结构:
aifund/
│
├── src/
│ └── aifund/
│ ├── __init__.py
│ └── core.py
│
├── tests/
│ └── test_core.py
│
├── pyproject.toml
├── README.md
├── LICENSE
└── setup.cfg
🧱 三、编写包代码
src/aifund/__init__.py
__version__ = "0.1.0"
from .core import say_hello
src/aifund/core.py
def say_hello(name: str) -> str:
"""
Returns a friendly greeting.
"""
return f"Hello, {name}! Welcome to aifund."
🧪 四、简单测试
tests/test_core.py
from aifund import say_hello
def test_say_hello():
assert say_hello("Alice") == "Hello, Alice! Welcome to aifund."
你可以用 pytest 测试:
pip install pytest
pytest tests
⚙️ 五、配置文件
pyproject.toml
(新版推荐用
pyproject.toml代替旧的setup.py)
[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"
setup.cfg
定义包的元数据
[metadata]
name = aifund
version = 0.1.0
author = mit
author_email = your_email@example.com
description = A simple AI utility toolkit named aifund
long_description = file: README.md
long_description_content_type = text/markdown
url = https://github.com/yourname/aifund
license = MIT
classifiers =
Programming Language :: Python :: 3
License :: OSI Approved :: MIT License
Operating System :: OS Independent
[options]
package_dir =
= src
packages = find:
python_requires = >=3.8
[options.packages.find]
where = src
LICENSE
可以使用 MIT 许可证(最简单的开源许可):
MIT License
Copyright (c) 2025
Permission is hereby granted, free of charge, to any person obtaining a copy
...
🏗️ 六、构建打包
执行以下命令:
python -m build
生成:
dist/
├── aifund-0.1.0-py3-none-any.whl
└── aifund-0.1.0.tar.gz
🚀 七、上传到 PyPI
1. 注册账号
前往 https://pypi.org/account/register/ 注册。
2. 创建 API Token
-
点击“Add API token”,选择“Entire account”
-
得到一个形如:
pypi-AgEIcHlwaS5vcmcCJG...的 Token。
3. 上传包
在命令行执行:
twine upload dist/* -u __token__ -p pypi-AgEIcHlwaS5vcmcCJG...
上传成功后,你会看到类似:
Uploading distributions to https://upload.pypi.org/legacy/
100%|██████████████████████████| 10.0k/10.0k
View at:
https://pypi.org/project/aifund/
✅ 八、安装验证
在任何地方都可以通过:
pip install aifund
然后测试:
>>> from aifund import say_hello
>>> say_hello("World")
'Hello, World! Welcome to aifund.'
💡 九、附加建议
| 目的 | 工具 |
|---|---|
| 测试上传 | https://test.pypi.org + twine upload --repository testpypi dist/* |
| 自动构建发布 | GitHub Actions |
| 文档网站 | mkdocs |
| 类型提示检查 | mypy |
| 自动版本控制 | bumpver or setuptools_scm |
更多推荐


所有评论(0)