PyPI

PyPI(Python Package Index)是Python官方的第三方软件包平台,用于存储和分发python的软件包。pip默认从PyPI平台下载安装软件包。

时间轴

发布包到pypi

注册pypi账号

pypi官网注册一个账号

打包项目

简单项目打包结构

packaging_tutorial/
  your_project/
    __init__.py
  setup.py
  LICENSE
  README.md

其中:

  • your_project,是项目文件夹
  • setup.py,是告诉setuptools关于包的信息,如名称,版本,包含哪些代码文件夹等。
  • LICENSE,文件为该项目的许可协议
  • README.md,该项目的说明

编写setup.py

一个简单的setup.py如下:

import setuptools

with open("README.md", "r") as fh:
    long_description = fh.read()

setuptools.setup(
    name="example-pkg-YOUR-USERNAME-HERE", # Replace with your own username
    version="0.0.1",
    author="Example Author",
    author_email="author@example.com",
    description="A small example package",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/pypa/sampleproject",
    packages=setuptools.find_packages(),
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
    python_requires='>=3.6',
)

编写LICENSE

编写许可协议,告诉安装该包的用户,他们能如何使用。可以在https://choosealicense.com/ 选择一个协议复制到LICENSE文件中,如下面的 MIT license:

Copyright (c) 2018 The Python Packaging Authority

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

编写README.md

可以用Markdown书写该项目的说明,如:

# Example Package

This is a simple example package. You can use
[Github-flavored Markdown](https://guides.github.com/features/mastering-markdown/)
to write your content. 

生成发行包

  • 首先确认安装了最新的setuptools和wheel
python3 -m pip install --user --upgrade setuptools wheel
  • 在setup.py所在文件夹运行下面命令打包:
python3 setup.py sdist bdist_wheel
  • 生成的发行包位于该文件夹下的dist文件夹,dist文件夹包含两个文件,如:
dist/
  example_pkg_YOUR_USERNAME_HERE-0.0.1-py3-none-any.whl
  example_pkg_YOUR_USERNAME_HERE-0.0.1.tar.gz

了解更多 >> Python文档-打包项目


上传包

安装twine:

pip install twine

在项目文件夹,运行命令上次dist文件夹下所有内容:

twine upload dist/*

资源

官网

参考文献