Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Đóng gói và xuất bản code Python (Packaging & Publishing)

Python cung cấp quy trình chuẩn để đóng gói và xuất bản package lên PyPI (Python Package Index).

Công cụ chính

  • pip: Package installer, quản lý dependency.
  • setuptools: Build/package distribution.
  • wheel: Binary distribution format (nhanh hơn source).
  • twine: Upload package lên PyPI an toàn.

Quy trình từng bước

Bước 1: Chuẩn bị cấu trúc package

my_package/
├── my_package/
│   ├── __init__.py
│   └── module.py
├── README.md
├── LICENSE.txt
├── setup.py
├── setup.cfg
└── pyproject.toml (optional)

Bước 2: Tạo setup.py

import setuptools

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

setuptools.setup(
    name="my_package",
    version="0.0.1",
    author="Your Name",
    author_email="you@example.com",
    description="Short description",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/yourname/my_package",
    packages=setuptools.find_packages(),
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
    python_requires=">=3.6",
    install_requires=[
        "requests>=2.25",
        # dependencies khác
    ],
)

Bước 3: Build distribution

pip install --upgrade setuptools wheel twine
python setup.py sdist bdist_wheel

Tạo thư mục dist/ chứa .tar.gz (source) và .whl (wheel).

Bước 4: Test cài đặt local

# Tạo virtual env test
python -m venv test_env
source test_env/bin/activate  # Windows: test_env\Scripts\activate
pip install dist/my_package-0.0.1.tar.gz
# Hoặc pip install dist/my_package-0.0.1-py3-none-any.whl

Bước 5: Upload lên PyPI

# Test trên TestPyPI trước
twine upload --repository testpypi dist/*

# Upload lên PyPI chính thức
twine upload dist/*

Nhập username/password PyPI (hoặc dùng API token).

pyproject.toml (Modern, PEP 517/518)

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

[project]
name = "my_package"
version = "0.0.1"
description = "Short description"
readme = "README.md"
authors = [{name = "Your Name", email = "you@example.com"}]
license = {text = "MIT"}
classifiers = [
    "Programming Language :: Python :: 3",
    "License :: OSI Approved :: MIT License",
]
requires-python = ">=3.6"
dependencies = ["requests>=2.25"]

[project.urls]
Homepage = "https://github.com/yourname/my_package"
Repository = "https://github.com/yourname/my_package"

Versioning

Tuân thủ Semantic Versioning: MAJOR.MINOR.PATCH (ví dụ 1.2.3).

Best Practices

  • Dùng src/ layout: src/my_package/ tránh import nhầm khi test.
  • Chứa LICENSE, README.md, CHANGELOG.md.
  • Dùng Git tags cho version: git tag v0.0.1.
  • CI/CD: GitHub Actions tự động test và publish.