Back

Python 项目打包与分发

工具

  • pip, setuptools, twine
python -m pip install --upgrade pip build twine

项目组织结构

packaging_tutorial/
├── LICENSE
├── pyproject.toml
├── README.md
├── setup.cfg
├── src/
│   └── example_package/
│       ├── __init__.py
│       └── example.py
└── tests/

配置文件

pyproject.toml

[build-system]
requires = [
    "setuptools>=51",
    "wheel"
]
build-backend = "setuptools.build_meta"

setup.cfg

[metadata]
name = example-pkg
version = 0.0.1
author = Example Author
author_email = author@example.com
description = A small example package
long_description = file: README.md
long_description_content_type = text/markdown
url = https://github.com/pypa/sampleproject
project_urls =
    Bug Tracker = https://github.com/pypa/sampleproject/issues
classifiers =
    Programming Language :: Python :: 3
    License :: OSI Approved :: MIT License
    Operating System :: OS Independent

[options]
package_dir =
    = src
packages = find:
python_requires = >=3.7
install_requires = 
    numpy==1.21.0
    Pillow==8.3.1

[options.packages.find]
where = src

[options.entry_points]
console_scripts =
    executable-name = example_pkg.__main__:main

打包并发布

打包

python -m build

生成以下包。

dist/
  example_package_YOUR_USERNAME_HERE-0.0.1-py3-none-any.whl
  example_package_YOUR_USERNAME_HERE-0.0.1.tar.gz

发布

python -m twine upload --repository testpypi dist/*
python -m twine upload --repository pypi dist/*

手动输入用户名及密码,或使用环境变量 TWINE_USERNAMETWINE_PASSWORD

如果使用 API Token,则以 __token__ 为用户名。

参考资料

Licensed under CC BY-NC-SA 4.0