本文以xuzhao-markdown-editor为例,详细介绍和如何将Python项目打包并上传PyPI仓库的过程。
xuzhao-markdown-editor项目结构如下:
|-- xuzhao-markdown-editor
|-- LICENSE
|-- MANIFEST.in
|-- README.rst
|-- requirements.txt
|-- setup.py
|-- xuzhao_markdown
|-- __init__.py
|-- static
|-- templates
setup.py是setuptools的构建脚本。它会告诉setuptools包信息(例如名称和版本)以及要包含的代码文件。
创建并打开setup.py并输入一下内容,可以根据打包需求填写相关的值:
import setuptools
with open('README.rst', 'r', encoding='utf8') as fh:
long_description = fh.read()
setuptools.setup(name='xuzhao-markdown-editor',
version='1.0',
description='xuzhao markdown editor',
long_description=long_description,
long_description_content_type="text/markdown",
author='xuzhao',
author_email='[email protected]',
url='https://markdown.felinae.net',
keywords='django markdown editor editormd',
packages=setuptools.find_packages(),
zip_safe=False,
include_package_data=True,
classifiers=(
"Programming Language :: Python",
"Development Status :: 4 - Beta",
"Operating System :: OS Independent",
"License :: OSI Approved :: Apache Software License",
"Framework :: Django"
))
关于classifiers的完整信息请查阅 https://pypi.org/classifiers/ 。
上传到PyPI的每一个包都包含许可证,这一点很重要。它告诉用户安装使用该软件包的条款。有关选择许可证的帮助,请参阅 https://choosealicense.com/ 。本文使用的是Apache许可证,内容如下:
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
······
Copyright 2018 徐昭
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
MANIFEST.in文件定义了需要额外打包的文件列表,内容如下:
include README.rst
include LICENSE
recursive-include xuzhao_markdown/static *
recursive-include xuzhao_markdown/templates *
具体格式和参数参考 https://docs.python.org/2/distutils/sourcedist.html 。
python -m pip install --user --upgrade setuptools wheel
python setup.py sdist bdist_wheel
命令执行成功后将生成如下文件:为了让其他用户能够通过pip工具安装使用您的python包,我们需要将分发档案上传到PyPI仓库。
进入PyPI官网注册一个PyPI账户,上传软件包时,需要验证您的账户。
twine配置文件
[distutils]
index-servers =
pypi
pypitest
[pypi]
username:PyPI用户名
password:PyPI密码
[pypitest]
repository: https://test.pypi.org/legacy/
username:PyPI用户名
password:PyPI密码
上传分发档案
twine upload dist/*
上传成功后,可以在个人中心查看该项目