1. 程式人生 > 其它 >如何將Python專案釋出到PyPI

如何將Python專案釋出到PyPI

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

如何打包可以參考官方文件,如果看英文比較費勁,參考這個譯文。也可以參考官方提供的例子

建立專案

  1. 目錄結構

    複製├── LICENSE.txt
    ├── MANIFEST.in
    ├── README.md
    ├── pyproject.toml
    ├── setup.cfg
    ├── setup.py
    └── app
    	├── __init__.py
    	└── app.py
    

接下來我們來逐一編寫除了程式碼以外的檔案。

  1. README.md

    是關於專案的描述檔案,一般包含怎樣安裝專案,怎樣使用專案等。markdown 語法可以參考adam-p/markdown-here

  2. LICENSE.txt

    開源License,如MIT,Apache license 2.0等。關於專案用什麼License,可參考Choose an open source license

  3. setup.cfg

    一個配置資訊檔案,執行setup.py程式打包的時候會用到裡面的配置,作為setup.py的命令列引數。內容如下

    複製[metadata]
    # This includes the license file(s) in the wheel.
    # https://wheel.readthedocs.io/en/stable/user_guide.html#including-license-files-in-the-generated-wheel-file
    license_files = LICENSE.txt
    desciption-file = README.md
    
    [bdist_wheel]
    # This flag says to generate wheels that support both Python 2 and Python
    # 3. If your code will not run unchanged on both Python 2 and 3, you will
    # need to generate separate wheels for each Python version that you
    # support. Removing this line (or setting universal to 0) will prevent
    # bdist_wheel from trying to make a universal wheel. For more see:
    # https://packaging.python.org/guides/distributing-packages-using-setuptools/#wheels
    universal=1
    

    關於setup.cfg更詳細的資訊,可參考Building and Distributing Packages with Setuptools

  4. setup.py

    用來描述專案,打包的時候會用到這個檔案。它告訴PyPI我們的專案叫什麼名字,是什麼版本,依賴哪些庫,支援哪些作業系統,可以在哪些版本的Python上執行,等等

    複製"""A setuptools based setup module.
    See:
    https://packaging.python.org/guides/distributing-packages-using-setuptools/
    https://github.com/pypa/sampleproject
    """
    import setuptools
    import os
    
    CUR_DIR = os.path.abspath(os.path.dirname(__file__))
    README = os.path.join(CUR_DIR, "README.md")
    with open("README.md", "r") as fd:
        long_description = fd.read()
    
    # Arguments marked as "Required" below must be included for upload to PyPI.
    # Fields marked as "Optional" may be commented out.
    
    setuptools.setup(
        # This is the name of your project. The first time you publish this
        # package, this name will be registered for you. It will determine how
        # users can install this project, e.g.:
        #
        # $ pip install sampleproject
        #
        # And where it will live on PyPI: https://pypi.org/project/sampleproject/
        #
        # There are some restrictions on what makes a valid project name
        # specification here:
        # https://packaging.python.org/specifications/core-metadata/#name
        # Required
        name = "tobe",
    
        # Versions should comply with PEP 440:
        # https://www.python.org/dev/peps/pep-0440/
        #
        # For a discussion on single-sourcing the version across setup.py and the
        # project code, see
        # https://packaging.python.org/en/latest/single_source_version.html
        # Required
        version = "0.1.2",
    
        # This is a one-line description or tagline of what your project does. This
        # corresponds to the "Summary" metadata field:
        # https://packaging.python.org/specifications/core-metadata/#summary
        # Optional
        description="A small ssh display tool",
    
        # This is an optional longer description of your project that represents
        # the body of text which users will see when they visit PyPI.
        #
        # Often, this is the same as your README, so you can just read it in from
        # that file directly (as we have already done above)
        #
        # This field corresponds to the "Description" metadata field:
        # https://packaging.python.org/specifications/core-metadata/#description-optional
        # Optional
        long_description=long_description,
    
        # Denotes that our long_description is in Markdown; valid values are
        # text/plain, text/x-rst, and text/markdown
        #
        # Optional if long_description is written in reStructuredText (rst) but
        # required for plain-text or Markdown; if unspecified, "applications should
        # attempt to render [the long_description] as text/x-rst; charset=UTF-8 and
        # fall back to text/plain if it is not valid rst" (see link below)
        #
        # This field corresponds to the "Description-Content-Type" metadata field:
        # https://packaging.python.org/specifications/core-metadata/#description-content-type-optional
        # Optional
        long_description_content_type="text/markdown",
    
        # This should be a valid link to your project's main homepage.
        #
        # This field corresponds to the "Home-Page" metadata field:
        # https://packaging.python.org/specifications/core-metadata/#home-page-optional
        # Optional
        url="https://github.com/PoplarYang/tobe",
    
        # This should be your name or the name of the organization which owns the
        # project.
        # Optional
        author="PoplarYang",
    
        # This should be a valid email address corresponding to the author listed
        # above.
        # Optional
        author_email="[email protected]",
    
        # You can just specify package directories manually here if your project is
        # simple. Or you can use find_packages().
        #
        # Alternatively, if you just want to distribute a single Python file, use
        # the `py_modules` argument instead as follows, which will expect a file
        # called `my_module.py` to exist:
        #
        #   py_modules=["my_module"],
        #
        # Required
        packages = ["tobe"],
        #packages=setuptools.find_packages(),
    
        # This field lists other packages that your project depends on to run.
        # Any package you put here will be installed by pip when your project is
        # installed, so they must be valid existing projects.
        #
        # For an analysis of "install_requires" vs pip's requirements files see:
        # https://packaging.python.org/en/latest/requirements.html
        # Optional
        install_requires = [
            "colorama>=0.4.1"
        ],
    
        # To provide executable scripts, use entry points in preference to the
        # "scripts" keyword. Entry points provide cross-platform support and allow
        # `pip` to create the appropriate form of executable for the target
        # platform.
        #
        # For example, the following would provide a command called `sample` which
        # executes the function `main` from this package when invoked:
        # Optional
        entry_points={
            'console_scripts': [
                'tobe=tobe:main'
            ],
        },
    
        # Specify which Python versions you support. In contrast to the
        # 'Programming Language' classifiers above, 'pip install' will check this
        # and refuse to install the project if the version does not match. If you
        # do not support Python 2, you can simplify this to '>=3.5' or similar, see
        # https://packaging.python.org/guides/distributing-packages-using-setuptools/#python-requires
        # Optional
        #python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, <4',
    
        # If there are data files included in your packages that need to be
        # installed, specify them here.
        #
        # If using Python 2.6 or earlier, then these have to be included in
        # MANIFEST.in as well.
        #package_data={  # Optional
        #    'sample': ['package_data.dat'],
        #},
    
        # Although 'package_data' is the preferred approach, in some case you may
        # need to place data files outside of your packages. See:
        # http://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files
        #
        # In this case, 'data_file' will be installed into '<sys.prefix>/my_data'
        # Optional
        #data_files=[('my_data', ['data/data_file'])],
    
        # Classifiers help users find your project by categorizing it.
        #
        # For a list of valid classifiers, see https://pypi.org/classifiers/
        # Optional
        classifiers=(
            # How mature is this project? Common values are
            #   3 - Alpha
            #   4 - Beta
            #   5 - Production/Stable
            'Development Status :: 3 - Alpha',
    
            # Indicate who your project is intended for
            'Intended Audience :: Developers',
            'Topic :: Software Development :: Build Tools',
    
            # Pick your license as you wish
            'License :: OSI Approved :: MIT License',
    
            # Specify the Python versions you support here. In particular, ensure
            # that you indicate whether you support Python 2, Python 3 or both.
            # These classifiers are *not* checked by 'pip install'. See instead
            # 'python_requires' below.
            'Programming Language :: Python :: 2',
            'Programming Language :: Python :: 2.7',
            'Programming Language :: Python :: 3',
            'Programming Language :: Python :: 3.5',
            'Programming Language :: Python :: 3.6',
            'Programming Language :: Python :: 3.7',
            'Programming Language :: Python :: 3.8',
            "Programming Language :: Python",
        ),
    
        # This field adds keywords for your project which will appear on the
        # project page. What does your project relate to?
        #
        # Note that this is a string of words separated by whitespace, not a list.
        # Optional
        keywords='ssh linux',
    
        # When your source code is in a subdirectory under the project root, e.g.
        # `src/`, it is necessary to specify the `package_dir` argument.
        # Optional
        #package_dir={'': 'src'},
        # List additional URLs that are relevant to your project as a dict.
        #
        # This field corresponds to the "Project-URL" metadata fields:
        # https://packaging.python.org/specifications/core-metadata/#project-url-multiple-use
        #
        # Examples listed include a pattern for specifying where the package tracks
        # issues, where the source is hosted, where to say thanks to the package
        # maintainers, and where to support the project financially. The key is
        # what's used to render the link text on PyPI.
        #project_urls={  # Optional
        #    'Bug Reports': 'https://github.com/pypa/sampleproject/issues',
        #    'Funding': 'https://donate.pypi.org',
        #    'Say Thanks!': 'http://saythanks.io/to/example',
        #    'Source': 'https://github.com/pypa/sampleproject/',
        #},
    )
    
    • name - 專案的名稱
    • version - 專案的版本。需要注意的是,PyPI上只允許一個版本存在,如果後續程式碼有了任何更改,再次上傳需要增加版本號
    • author和author_email - 專案作者的名字和郵件
    • description - 專案的簡短描述
    • long_description - 專案的詳細描述,會顯示在PyPI的專案描述頁面。上面的例子裡直接用了README.md中的內容做詳細描述
    • long_description_content_type - 用於指定long_description的markup型別,上面的例子是markdown
    • url - 專案主頁的URL,一般給出程式碼倉庫的連結
    • packages - 指定最終釋出的包中要包含的packages。上面的例子中find_packages() 會自動發現專案根目錄下所有的packages,當然也可以手動指定package的名字
    • install_requires - 專案依賴哪些庫,這些庫會在pip install的時候自動安裝
    • entry_points - 上面的例子中entry_points用來自動建立指令碼,上面的例子在pip install安裝成功後會建立tobe這個命令,直接可以在命令列執行,即執行tobe:main
    • classifiers - 其他資訊,一般包括專案支援的Python版本,License,支援的作業系統。上面的例子中,我們指定專案只能在Python 3上執行,使用MIT License,不依賴作業系統。關於classifiers的完整列表,可參考https://pypi.org/classifiers/
  5. MANIFEST.in

    記錄需要放在包中的除了程式碼之外的其他檔案。

    複製include pyproject.toml
    
    # Include the README
    include *.md
    
    # Include the license file
    include LICENSE.txt
    
    # Include the data files
    #recursive-include data *
    
  6. pyproject.toml

    在配置檔案中將會有一個[build-system]表來儲存與構建相關的資料。最初,表中只有一個關鍵字是有效的和必需的:requires。該鍵將包含一個字串列表的值,代表執行構建系統所需的PEP 508依賴.

    複製[build-system]
    # These are the assumed default build requirements from pip:
    # https://pip.pypa.io/en/stable/reference/pip/#pep-517-and-518-support
    requires = ["setuptools>=40.8.0", "wheel"]
    build-backend = "setuptools.build_meta"
    

打包專案

  1. 打包專案需要用到setuptools和wheel,先安裝這兩個庫
複製pip install setuptools
pip install wheel
  1. 安裝完後,執行下面的命令打包
複製python setup.py sdist bdist_wheel

上面的命令會在dist/目錄下生成一個tar.gz的原始碼包和一個.whl的Wheel包。

複製dist/
  *.whl
  *.tar.gz

打包完之後,我們可以從本地安裝庫,來驗證我們的專案能否被成功安裝,如下

複製pip install dist/*.whl

釋出專案到PyPI

使用twine上傳專案,先安裝twine

複製pip install twine

安裝完之後,執行下面的命令將庫上傳

複製twine upload dist/*

上傳完成後,我們的專案就成功地釋出到PyPI了。

這裡需要先註冊一個 PyPI 賬戶

附錄

  1. pypi 免密上傳,通過twine配置檔案實現。

    $HOME/.pypirc` file with your username and password:

    複製[pypi]
    username = <username>
    password = <password>
    

    不建議將密碼放入檔案中

  2. pypi 官方測試環境test.pypi.org。參考使用testpypi

  3. 直接從程式碼倉庫安裝python 包

    複製pip install -e git+https://git.repo/some_pkg.git#egg=SomeProject          # from git
    pip install -e hg+https://hg.repo/some_pkg#egg=SomeProject                # from mercurial
    pip install -e svn+svn://svn.repo/some_pkg/trunk/#egg=SomeProject         # from svn
    pip install -e git+https://git.repo/some_pkg.git@feature#egg=SomeProject  # from a branch
    
  4. 使 python 包在任何地方都能安裝

    This is a wheel that can be installed anywhere bypip.

    setup.cfg(e.g., seesampleproject/setup.cfg):

    複製[bdist_wheel]
    universal=1