欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python打包方法之setup.py與pyproject.toml的全面對比與實戰(zhàn)

 更新時間:2025年05月06日 09:25:23   作者:夢想畫家  
在 Python 開發(fā)中,創(chuàng)建可安裝的包是分享代碼的重要方式,本文將深入解析兩種主流打包方法——setup.py 和 pyproject.toml,并通過一個實際項目示例,展示如何使用現(xiàn)代的 pyproject.toml 方法構(gòu)建、測試和發(fā)布 Python 包,需要的朋友可以參考下

一、setup.py 與 pyproject.toml 的區(qū)別

1. setup.py(傳統(tǒng)方式)

setup.py 是 Python 打包的傳統(tǒng)方法,使用 setuptools 或 distutils 定義包的元數(shù)據(jù)和依賴關(guān)系。典型示例如下:

from setuptools import setup

setup(
    name='mypackage',
    version='0.1',
    packages=['mypackage'],
    install_requires=['requests']
)

使用方法

python setup.py sdist bdist_wheel
pip install .

2. pyproject.toml(現(xiàn)代方式)

自 PEP 518 引入后,pyproject.toml 成為推薦的配置方式。它分離了構(gòu)建系統(tǒng)配置和包元數(shù)據(jù),支持多種構(gòu)建工具(如 setuptoolspoetry 等)。示例:

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

[project]
name = "mypackage"
version = "0.1"
dependencies = ["requests"]

使用方法

pip install .

二、為什么推薦 pyproject.toml?

  1. 標準化與兼容性:符合最新打包標準,與各種工具兼容性更好。
  2. 簡化配置:分離構(gòu)建系統(tǒng)和元數(shù)據(jù),使配置更清晰。
  3. 多構(gòu)建系統(tǒng)支持:支持多種工具,提供更大靈活性。
  4. 安全性:減少對自定義腳本的依賴,降低風險。

實際場景中的必要性

假設(shè)你正在開發(fā)一個復雜的機器學習庫,涉及多個依賴項和復雜的構(gòu)建步驟。使用 pyproject.toml 可以輕松定義這些需求,并確保在不同的開發(fā)和部署環(huán)境中保持一致性。此外,許多現(xiàn)代工具(如 CI/CD 系統(tǒng))已經(jīng)內(nèi)置了對 pyproject.toml 的支持,簡化了自動化流程。

構(gòu)建 Python 包的最佳實踐

  1. 新項目使用 pyproject.toml:對于新項目,推薦使用 pyproject.toml,以符合現(xiàn)代打包標準并提高兼容性。
  2. 舊項目逐步遷移:如果維護的是已有使用 setup.py 的項目,可以繼續(xù)使用,但建議在可行時遷移到 pyproject.toml。
  3. 結(jié)合使用:在某些情況下,可以同時使用 pyproject.toml 和 setup.py,例如用 pyproject.toml 處理大部分配置,而保留一個最小化的 setup.py 來處理特定功能(如構(gòu)建 C 擴展)。
  4. 使用 setup.cfg:如果希望采用更聲明式的格式但仍使用 setup.py,可以考慮使用 setup.cfg,將元數(shù)據(jù)放在配置文件中,邏輯保留在 setup.py 中。
  5. 利用構(gòu)建工具:使用如 Poetry 或 Flit 等工具,可以簡化依賴管理和打包流程,自動管理 pyproject.toml 和其他相關(guān)文件的創(chuàng)建。

三、實戰(zhàn)示例:構(gòu)建和發(fā)布一個機器學習包

下面通過一個實際的機器學習項目示例,展示如何使用 pyproject.toml 構(gòu)建、測試和發(fā)布一個 Python 包。

項目概述

我們將構(gòu)建一個名為 mlpredictor 的包,該包:

  • 包含一個使用 scikit-learn 的簡單分類器模型。
  • 提供訓練模型和進行預測的功能。
  • 結(jié)構(gòu)化以便發(fā)布到 PyPI 和 GitHub。

步驟詳解

1. 創(chuàng)建項目結(jié)構(gòu)

mlpredictor/
│
├── mlpredictor/
│   ├── __init__.py
│   ├── model.py
│
├── tests/
│   ├── test_model.py
│
├── LICENSE
├── README.md
├── pyproject.toml
└── .gitignore

2. 編寫代碼

mlpredictor/model.py

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
import pickle


class MLPredictor:
    def __init__(self):
        self.model = None

    def train(self):
        iris = load_iris()
        X_train, X_test, y_train, y_test = train_test_split(
            iris.data, iris.target, test_size=0.2, random_state=42
        )
        self.model = RandomForestClassifier()
        self.model.fit(X_train, y_train)

    def predict(self, data):
        if not self.model:
            raise Exception("Model is not trained yet!")
        return self.model.predict([data])

    def save_model(self, path="model.pkl"):
        with open(path, "wb") as f:
            pickle.dump(self.model, f)

    def load_model(self, path="model.pkl"):
        with open(path, "rb") as f:
            self.model = pickle.load(f)

mlpredictor/*init*.py

from .model import MLPredictor

__all__ = ["MLPredictor"]

3. 創(chuàng)建 pyproject.toml 文件

pyproject.toml

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

[project]
name = "mlpredictor"
version = "0.1.0"
description = "A simple machine learning package using scikit-learn"
authors = [
    {name = "Ebrahim", email = "ebimsv0501@gmail.com"}
]
license = {text = "MIT"}
readme = "README.md"
requires-python = ">=3.6"
dependencies = [
    "scikit-learn>=1.0",
]

[project.urls]
"Homepage" = "https://github.com/xxx_your_account/mlpredictor"
  • [build-system]:指定構(gòu)建系統(tǒng)要求,這里使用 setuptools 和 wheel
  • [project]:包含包的元數(shù)據(jù),如名稱、版本、描述、作者、許可證、依賴項等。

4. 編寫測試

使用 pytest 添加測試。

tests/test_model.py

import pytest
from mlpredictor import MLPredictor

def test_train_and_predict():
    model = MLPredictor()
    model.train()
    result = model.predict([5.1, 3.5, 1.4, 0.2])
    assert len(result) == 1

if __name__ == "__main__":
    pytest.main()

5. 添加 README、License 和 .gitignore

README.md

# MLPredictor

MLPredictor 是一個簡單的機器學習包,使用 scikit-learn 訓練 RandomForest 模型,并使用戶能夠進行預測。該包旨在演示如何打包 Python 機器學習項目以供分發(fā)。

## 特性

- 在 Iris 數(shù)據(jù)集上訓練 RandomForestClassifier。
- 訓練后對新數(shù)據(jù)進行預測。
- 保存和加載訓練好的模型。

## 安裝

您可以通過 **PyPI** 或從 **源代碼** 安裝該包。

### 通過 PyPI 安裝

```bash
pip install mlpredictor

通過源代碼安裝(GitHub)

git clone https://github.com/xxx_your_account/mlpredictor.git
cd mlpredictor
pip install .

使用方法

安裝后,可以使用 MLPredictor 訓練模型并進行預測。

示例:訓練和預測

from mlpredictor import MLPredictor

# 初始化預測器
predictor = MLPredictor()

# 在 Iris 數(shù)據(jù)集上訓練模型
predictor.train()

# 對樣本輸入進行預測
sample_input = [5.1, 3.5, 1.4, 0.2]
prediction = predictor.predict(sample_input)

print(f"預測類別: {prediction}")

LICENSE

可以選擇合適的開源許可證,如 MIT License。

.gitignore

*.pyc
__pycache__/
*.pkl
dist/
build/

6. 本地測試包

通過以下命令安裝包:

pip install .

安裝后,運行測試以確保一切正常:

pytest tests

注意

  • 如果使用 setup.py,它會讀取 setup.py 文件以收集包元數(shù)據(jù)和安裝信息,并解析和安裝指定的依賴項。

  • 如果使用pyproject.toml ,它會讀取該文件,可能指定構(gòu)建系統(tǒng)要求和配置。執(zhí)行上述命令后,通常會創(chuàng)建以下目錄:

    • Distribution Directory:可能是 build/、dist/ 或 .eggs/ 目錄,具體取決于安裝過程以及是源碼安裝還是 wheel 安裝。
    • build/:在構(gòu)建過程中創(chuàng)建,包含用于創(chuàng)建包的臨時文件。
    • dist/:包含從包生成的構(gòu)建分發(fā)文件(如 wheel 文件)。
    • egg-info/ 或 .egg-info/:包含有關(guān)已安裝包的元數(shù)據(jù),包括其依賴項和版本號。

確保項目正常工作后,繼續(xù)后續(xù)步驟。

7. 推送到 GitHub

  1. 初始化 Git 倉庫

git init
git add .
git commit -m "Initial commit"
  • 創(chuàng)建 GitHub 倉庫

    前往 GitHub 并創(chuàng)建一個名為 mlpredictor 的新倉庫。

  • 推送代碼到 GitHub

git remote add origin https://github.com/xxx_your_account/mlpredictor.git
git branch -M main
git push -u origin main
  • 注意:將 xxx_your_account 替換為您的 GitHub 用戶名。

8. 發(fā)布到 PyPI

現(xiàn)在項目已經(jīng)設(shè)置并推送到 GitHub,可以將其發(fā)布到 PyPI。

安裝必要的工具

pip install twine build

構(gòu)建包

python -m build

這將在 dist/ 目錄下創(chuàng)建 .tar.gz 和 .whl 文件。檢查 dist/ 目錄,確保包含類似以下文件:

mlpredictor-0.1.0-py3-none-any.whl
mlpredictor-0.1.0.tar.gz

上傳到 PyPI

twine upload dist/*

您需要一個 PyPI 賬戶才能上傳包。上傳成功后,其他人可以通過以下命令安裝您的包:

pip install mlpredictor

9. 安裝并使用包

通過 pip 安裝后,可以在 Python 代碼中使用該包:

from mlpredictor import MLPredictor

predictor = MLPredictor()
predictor.train()
prediction = predictor.predict([5.1, 3.5, 1.4, 0.2])
print("Predicted class:", prediction.item())

# 輸出示例:
# Predicted class: 0

五、總結(jié)

在 Python 打包領(lǐng)域,setup.py 和 pyproject.toml 各有其重要性和適用場景。盡管 setup.py 在傳統(tǒng)項目中仍然發(fā)揮作用,但向 pyproject.toml 的轉(zhuǎn)變代表了 Python 社區(qū)向更安全、標準化實踐發(fā)展的趨勢。對于新項目,強烈建議采用 pyproject.toml,因為它不僅簡化了打包過程,還提高了與各種工具和庫的兼容性。

通過本文的實戰(zhàn)示例,您應該能夠掌握如何使用 pyproject.toml 構(gòu)建、測試和發(fā)布一個功能完善的 Python 包。無論是個人項目還是團隊協(xié)作,遵循這些最佳實踐將大大提升項目的可維護性和可擴展性。

以上就是Python打包方法之setup.py與pyproject.toml的全面對比與實戰(zhàn)的詳細內(nèi)容,更多關(guān)于Python setup.py與pyproject.toml對比的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論