11 发布你的 Python 代码给别人 “pip instal
参考资料:Packaging Python Projects
使用环境:Windows10.
首先需要在 PyPI 注册一个账号,接着您需要将您的代码组织成包的形式,比如:
图1 PyPI 上传需要准备的文件在图1 graph_tensor
以 Python 的“包”的形式进行组织,然后在其同级目录放入文件 LICENSE
、README.md
、setup.py
。其中 LICENSE
用于编写您的代码遵循的协议,README.md
用于编写您的项目介绍。下面主要介绍 setup.py
。
import setuptools
with open("README.md", "r", encoding='utf-8') as fh:
long_description = fh.read()
setuptools.setup(
name="graph-tensor", # Replace with your own username
version="0.0.1",
author="XXX",
author_email="XXX@qq.com",
description="A universal graphics library",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/TensorAtom/Graph",
packages=setuptools.find_packages(),
classifiers=[
"Programming Language :: Python :: 3",
"Development Status :: 2 - Pre-Alpha",
"License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)",
"Operating System :: Microsoft :: Windows :: Windows 10",
"Operating System :: Microsoft :: Windows :: Windows 7",
"Operating System :: POSIX :: Linux"
],
python_requires='>=3.7',
)
上述的代码设定了 PyPI 的描述文档 long_description
为 "README.md"
,long_description_content_type="text/markdown"
表示支持 Markdown 作为描述。classifiers
参数之外,其他的都很容易理解。classifiers
是什么呢?其实 classifiers
为索引和 pip 提供一些有关包的附加元数据,表示程序的所属分类列表(https://pypi.org/classifiers/)。
打包
打包很简单,只需要执行:
$ python setup.py sdist bdist_wheel
此时您的目录下会生成几个新的目录,我们只关心 dist/
。该目录存在两个文件 *.tar.gz
(源存档)和 .whl
(构建的分发版本)。
使用 twine 上传 PyPI
首先安装或者更新 twine
:
python -m pip install --user --upgrade twine
其次,注册 TestPyPI,您使用的是 TestPyPI,Python 包索引的单独实例,允许您尝试分发工具和进程,而不会影响实际索引。类似于一种测试机制。
上传的方式:
$ python -m twine upload --repository-url https://test.pypi.org/legacy/ dist/*
上传到了 TestPyPI,您可以看到类似如下的网页:
图2 TestPyPI 界面点击复制安装命令,在您的电脑测试是否安装成功。
此时上传需要使用 --repository-url
参数,为了去掉该参数,需要我们正式上传源码到 PyPI,即运行:
$ python -m twine upload dist/*
上传结束便可以看到如下网页:
图3 正式上传到 PyPI此时,便可以使用简便的方式安装包了。
如果在配置过程出现问题,可以访问https://github.com/pypa/packaging-problems/issues。
一个 Bug
如果您配置了 PyPI 的清华镜像,可能无法直接使用 pip install
,需要使用 pip install -i https://pypi.org/simple/ graph-tensor==0.0.2
的方式进行安装。这只是临时的方法,为了永久生效,可以修改设置:
$ pip config set global.index-url https://pypi.org/simple/
或者解除设置:
$ pip config unset global.index-url