美文网首页Python WebPython
PyPI - 如何打包Python代码为PIP包

PyPI - 如何打包Python代码为PIP包

作者: 红薯爱帅 | 来源:发表于2019-06-07 20:18 被阅读0次

    1. 前言

    Python Package,在实际项目中应用广泛,包含Public Package和Private Package。它有助于我们对代码进行功能封装,使得软件更加结构化、有序化、层次化。主要有几个应用场景:

    • 微服务架构下,底层的Core Module,例如
      • notification_client,可以支持多种通知方式,方便快捷
      • passport_client,大部分portal服务需要的认证client,一改全改,便于维护
      • payment_client,封装对多种支付方式的支持,例如alipay、wechat等,基本不变动
    • Saas的Python SDK,pip install后即可使用

    2. 如何打包Python Package

    2.1. Creating the package files

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

    2.2. Generating distribution archives

    • make sure you have the latest versions of setuptools and wheel installed
    $ python3 -m pip install --user --upgrade setuptools wheel
    
    • run this command from the same directory where setup.py is located, and will generate two files in the dist directory
    $ python3 setup.py sdist bdist_wheel
    $ tree dist/
    dist/
    ├── example_pkg_shuzhang-0.0.1-py3-none-any.whl
    ├── example-pkg-shuzhang-0.0.1.tar.gz
    ├── example_pkg_shuzhang-0.0.2-py3-none-any.whl
    └── example-pkg-shuzhang-0.0.2.tar.gz
    
    0 directories, 4 files
    

    2.3. Uploading the distribution archives

    • install twine for uploading the packages
    $ python3 -m pip install --user --upgrade twine
    
    • run Twine to upload all of the archives under dist, 3 examples as below
    $ python3 -m twine upload --repository-url https://upload.pypi.org/legacy/ dist/*
    $ python3 -m twine upload --repository-url https://test.pypi.org/legacy/ dist/*
    $ twine upload dist/*
    

    2.4. Just do some tests

    • install package using pip
    $ python3 -m pip install --index-url https://test.pypi.org/simple/
    $ pip install package-name==0.0.2
    
    • just enjoy it
    >>> import example_pkg
    >>> example_pkg.name
    'example_pkg'
    

    3. Reference

    相关文章

      网友评论

        本文标题:PyPI - 如何打包Python代码为PIP包

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