美文网首页Python技术文章
发布python库到pypi

发布python库到pypi

作者: blueshadow | 来源:发表于2017-04-20 23:10 被阅读200次

平时我们安装各种python库的时候只需要一句命令: pip install xxx。那到底如何才能使得自己的库支持这样的安装方法呢?

什么是pypi

引用自官网:

PyPI — the Python Package Index
The Python Package Index is a repository of software for the Python programming language.

创建账户

注意server存在两种,也就对应两种账号

  • PyPI Live
  • PyPI Test
    省得麻烦,这里推荐两个账号都使用相同的邮箱和密码。

创建配置文件

在你的HOME目录下创建这个文件:.pypirc,这个文件保存着与PYPI服务器认证信息。
内容大概长这样子:

[distutils]
index-servers =
  pypi
  pypitest

[pypi]
repository=https://pypi.python.org/pypi
username=your_username
password=your_password

[pypitest]
repository=https://testpypi.python.org/pypi
username=your_username
password=your_password

准备你的包

每一个PyPI上面的包都需要根目录下有这个文件:setup.py。如果你使用了一个markdown格式的README文件,你还需要包含文件setup.cfg。另外,你可能需要一个LICENSE.txt文件来描述你的代码使用许可申明。
假设你正在构建一个库叫mypackage,你的目录结构看起来大概是这样:

root-dir/   # arbitrary working directory name
  setup.py
  setup.cfg
  LICENSE.txt
  README.md
  mypackage/
    __init__.py
    foo.py
    bar.py
    baz.py

setup.py

这个是描述你库信息的信息。

from distutils.core import setup
setup(
  name = 'mypackage',
  packages = ['mypackage'], # this must be the same as the name above
  version = '0.1',
  description = 'A random test lib',
  author = 'Peter Downs',
  author_email = 'peterldowns@gmail.com',
  url = 'https://github.com/peterldowns/mypackage', # use the URL to the github repo
  download_url = 'https://github.com/peterldowns/mypackage/archive/0.1.tar.gz', # I'll explain this in a second
  keywords = ['testing', 'logging', 'example'], # arbitrary keywords
  classifiers = [],
)

download_url是你库代码托管位置的链接。Github可以帮你托管,但你必须创建一个git tag。在你的库中:git tag 0.1 -m "Adds a tag so that we can put this on PyPI."。然后,输入git tag显示一堆tags,其中你应该看到0.1。输入git push --tags origin master来提交关于最新的tag信息到Github上。Github将会创建用于下载的tarballs,其链接为https://github.com/{username}/{module_name}/archive/{tag}.tar.gz.

setup.cfg

这个文件告诉PyPi你的README文件在哪里:

[metadata]
description-file = README.md

如果你使用一个markdown格式的readme文件,那这个文件是必须要有的。在上传的时候,你可能还会得到一些关于readme文件缺失的错误,忽视就可以了。如果你并不需要使用一个markdown格式的README,这里推荐使用reStructuredText (REST)

LICENSE.txt

这个文件描述了你的代码使用什么样的license。我个人比较喜欢用 MIT license

上传包到PyPi Test

运行:

python setup.py register -r pypitest
python setup.py sdist upload -r pypitest

没有错误的话,你应该可以在 test PyPI repository上看到你的库了。

上传包到PyPi Live

一旦你成功地上传到PyPI Test后,你就可以用同样的步骤来上传到PyPI Live服务器:

python setup.py register -r pypi
python setup.py sdist upload -r pypi

大功告成!你的第一个包发布啦!

参考:
first-time-with-pypi

相关文章

网友评论

    本文标题:发布python库到pypi

    本文链接:https://www.haomeiwen.com/subject/fxrrzttx.html