开场白 pypi作为python pip
库的源,方便发布者分发内容 和使用者获取,使用者通过pip命令可以一键部署库。相较于java的库管理需要写xml,或者c++或c#需要将dll或头文件手动导入到项目中,pip可以说是最方便的工具了。
之前在写一个nonebot插件的时候有发布过pip包,但现在突然想填个坑,忘记了怎么发包。这篇文章旨在介绍pip包的发布方法,以便记录备忘。
接下来正式进入流程
流程 注册pypi 这一部分无需多言,相信看这篇文章的你一定是会的 进入pypi 注册一个就行了
获取api密钥 用上面注册的账号登录以后进入到账号设置
这里添加一个api token
,以便备用
进入到项目中 首先安装必要的库
pip install setuptools twine
setuptools
用于编写包的元信息格式和打包等便于上传
twine
用于认证账户和上传
我的项目结构是这样的
|-- project |-- LICENSE |-- README.md |-- setup.py |-- nonebot_plugin_wol | |-- __init__.py | |-- tools | |-- wol.py
其中LICENSE
, README.md
, nonebot_plugin_wol(项目文件)
是必须的
在项目中创建一个setup.py
的文件,文件内容如下
import osfrom setuptools import setup, find_packagesMAJOR =1 MINOR =1 PATCH =0 VERSION = f"{MAJOR} .{MINOR} .{PATCH} " fp = open ('README.md' ,encoding="utf-8" ) setup( name="nonebot_plugin_wol" , version=VERSION, author="TwoOnefour" , author_email="twoonefour@pursuecode.cn" , long_description_content_type="text/markdown" , url='https://github.com/twoonefour/nonebot_plugin_wol.git' , long_description=fp.read(), python_requires=">=3.9" , install_requires=['ping3>=4.0.4' , "nonebot2>=2.0.0rc2" , "nb-cli>=0.6.8" , "nonebot-plugin-apscheduler>=0.2.0" ], packages=find_packages(), license='MIT License' , classifiers=[ 'Natural Language :: English' , 'Operating System :: OS Independent' , 'Programming Language :: Python :: 3.6' , 'Topic :: Software Development :: Libraries :: Python Modules' , ], package_data={'' : ["tools/*.py" ]}, include_package_data=True ) fp.close()
写好setup.py
后,直接运行
python setup.py sdist
这会在当前文件夹下生成一个dist
文件夹,当前目录会变成这样
|-- project |-- LICENSE |-- README.md |-- setup.py |-- nonebot_plugin_wol | |-- __init__.py | |-- tools | |-- wol.py |-- dist |-- nonebot_plugin_wol-1.1.0.tar.gz
接下来设置好你的认证密钥,进入到你的用户根目录下
windows
对应根目录C:/Users/<你的用户名>
linux
对应根目录~
(你都用linux了我觉得也不用多说了,应该知道的)
创建一个.pypirc
的文件,内容如下
[distutils] index-servers = pypi # 这里对应下面的节,也可以改名 nonebot_plugin_wol # 这里对应下面的节,也可以改名 testpypi # 一般来说正式发布前建议只使用这个源,查看没问题后再上传其他的 [pypi] username = __token__ password = pypi-xxxxxx # a user-scoped token or a project-scoped token you want to set as the default [nonebot_plugin_wol] repository = https://upload.pypi.org/legacy/ username = __token__ password = pypi-xxxxxxxxxxxxxxxxxxxxxx [testpypi] repository = https://test.pypi.org/legacy/ username = __token__ password = pypi-xxxxxxxxxxxxxxxxxxxxxx
这上面只需要把pypi-xxxx
修改为上面步骤获取的api token
即可
保存后就可以上传了
twine upload dest/*
输完以后就上传到pypi源了
可以用pip install <你的项目名>
确认一下
我这里是
pip install nonebot_plugin_wol
pypi库对应的网站
需要注意的是库刚上传,类似清华源的这些镜像站可能还没有同步 ,如果你使用其他源非官方源有可能会出现拉取不了的情况