0x00、简介
The Python Package Index, abbreviated as PyPI and also known as the Cheese Shop (a reference to the Monty Python’s Flying Circus sketch Cheese Shop),[1][2] is the official third-party software repository for Python.[3] It is analogous to CPAN, the repository for Perl.[4] Some package managers, including pip, use PyPI as the default source for packages and their dependencies.[5][6] Over 113,000 Python packages can be accessed through PyPI.[7]
就是说 PyPI(Python Package Index) 是 Python 官方的第三方库,所有人都可以下载或上传 Python 库到 PyPI。
0x01、流程
1、注册账号
想要上传自己的 Python 包没 PyPI 账号怎么行!官网地址
2、项目架构
a、项目环境:
- python3
- pip
- setuptools
- wheel
- twine
b、项目文件
如果想上传一个名为 “debug_world” 的 Python 包,那么她的项目文件如下:
1 | -- packaging_tutorial # 项目名字 |
print_str.py 文件实现三个功能,代码如下:
1 | def debug_world(): |
setup.py 文件代码如下:
1 | import setuptools |
这里是最简单的配置,有关详细信息,请参阅打包和分发项目。
c、本地打包
确保pip,setuptools 和 wheel 是最新的。
虽然 pip 就能够保证安装成功,但是最新的 setuptools 和 wheel 对安装有益无害。
While pip alone is sufficient to install from pre-built binary archives, up to date copies of the setuptools and wheel projects are useful to ensure you can also install from source archives:
1 | python -m pip install --upgrade pip setuptools wheel |
进入 setup.py 同级目录,然后运行打包程序
1 | # 运行setup.py |
此时项目会出现两个新文件:
d、上传PyPI
运行把 Python 包上传到 PyPI 的命令
1 | pip install twine # 如果已经安装twine,跳过次步骤 |
如果不想每次上传都输入账号和密码,可以创建用户验证文件 ~/.pypirc
1 | # 而且此方法不安全,容易泄露密码, 因为密码是明文 |
然后就可以去PyPI官网查看你的包是否成功上传了
3、验证
PyPI 推荐通过 pip 使用 Python 包
1 | pip install debug-world |
新建验证文件 verify_pypi.py
1 | from debug_world import print_str |
查看运行结果,说明成功了
1 | Hello, world |
4、删除版本
当想要删除某一版本的时候,只需在官网项目管理页面进行删除即可。
输入相对应的版本号。
0x02、注意事项
- 包名一定是别人没用过的
- 项目文件一定要有 init.py
- 运行setup.py文件一定要同级目录
- 在上传PyPI的是时候输入的是用户名和密码,不是邮箱和密码
- 上传之后需要等一段时间,才能下载最新版本的包
- 更改包的时候一定要修改版本号
- pip 按照版本号安装, ==前后没有空格
0x03、报错
HTTPError: 400 Client Error: File already exists: 版本号错误
HTTPError: 403 Client Error: Invalid or non-existent authentication information: 密码错误
error: invalid command ‘bdist_wheel’:
1 | # 升级pip的安装工具setuptools |