亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

python中whl文件封裝的實現(xiàn)示例

 更新時間:2025年08月24日 08:38:55   作者:青銅發(fā)條  
Wheel(.whl)是 Python 的一種內(nèi)置包格式,本文就來介紹一下python中whl文件封裝的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

一、Whl 包簡介

Wheel(.whl)是 Python 的一種內(nèi)置包格式,用于替代傳統(tǒng)的 egg 格式。它被設(shè)計為更快速安裝的替代方案,具有以下優(yōu)點:

  • 安裝速度快:預(yù)編譯格式,無需在安裝時執(zhí)行 setup.py
  • 更可靠:避免了執(zhí)行任意代碼的風(fēng)險
  • 支持二進(jìn)制分發(fā):可以包含編譯的擴(kuò)展文件
  • 現(xiàn)代標(biāo)準(zhǔn):是當(dāng)前 Python 包分發(fā)的推薦格式

二、準(zhǔn)備工具包

制作whl包需要依賴相應(yīng)的工具包,安裝方法如下:

pip install setuptools wheel twine
  • setuptools:用來打包你的項目,定義項目信息(名字、版本、依賴等)并生成分發(fā)文件(如 .whl 或 .tar.gz)。
  • wheel:一種高效的包格式(.whl 文件),安裝快、無需編譯,setuptools 用它來生成這種包。
  • twine:安全地將打包好的文件(.whl 或 .tar.gz)上傳到 PyPI 或私有倉庫。

三、詳細(xì)制作流程

為了方便演示,創(chuàng)建了一個加減乘除的方法例子來演示。

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

simple_math/
├── src/                     #源碼頂層目錄
│   └── simple_math/         #但功能模塊目錄
│       ├── __init__.py
│       ├── add.py           #加法
│       ├── sub.py           #減法
│       ├── mult.py          #乘法
│       └── div.py           #除法
├── test/
│   └── test_ops.py          #測試程序
├── examples/
│   └── example.py           #使用示例程序
├── README.md                #說明文檔
├── LICENSE                  #許可證
├── pyproject.toml           #
└── setup.py                 #打包配置文件

2、編寫包代碼

  • add.py文件:
def add(a: float, b: float) -> float:
    """
    將兩個數(shù)字相加
    
    Args:
        a (float): 第一個數(shù)字
        b (float): 第二個數(shù)字
        
    Returns:
        float: 兩個數(shù)字的和
    """
    return float(a + b)
  • sub.py 文件:
def sub(a: float, b: float) -> float:
    return float(a - b)
  • mult.py 文件:
def mult(a: float, b: float) -> float:
    return float(a * b)
  • div.py 文件:
def div(a: float, b: float) -> float:
    """
    將第一個數(shù)字除以第二個數(shù)字
    
    Args:
        a (float): 被除數(shù)
        b (float): 除數(shù)
        
    Returns:
        float: 兩個數(shù)字的商
        
    Raises:
        ZeroDivisionError: 當(dāng)除數(shù)為零時拋出
    """
    if b == 0:
        raise ZeroDivisionError("除數(shù)不能為零")
    return float(a / b)
  • src/simple_math/__init__.py文件:
"""
簡單數(shù)學(xué)計算包
提供加減乘除基本運算
"""

__version__ = "0.1.0"
__author__ = "your_name <your.email@example.com>"

# 導(dǎo)入所有功能,方便用戶直接使用
from .add import add
from .sub import sub
from .mult import mult
from .div import div

3、(可選)編寫測試代碼

  • test.py文件:
import pytest
from simple_math.add import add
from simple_math.sub import sub
from simple_math.mult import mult
from simple_math.div import div


class TestAdd:
    """測試加法功能"""

    def test_add(self):
        assert add(2, 3) == 5.0


class TestSub:
    """測試減法功能"""

    def test_sub(self):
        assert sub(5, 3) == 2.0

class TestMult:
    """測試乘法功能"""

    def test_mult_positive_numbers(self):
        assert mult(2, 3) == 6.0


class TestDiv:
    """測試除法功能"""

    def test_div(self):
        assert div(6, 3) == 2.0

    def test_div_by_zero(self):
        with pytest.raises(ZeroDivisionError):
            div(5, 0)

4、(可選)創(chuàng)建示例使用代碼

#!/usr/bin/env python3
from simple_math import add, sub, mult, div

def main():
    """演示所有功能的使用"""
    print("=== math_ops 包使用示例 ===\n")
    
    # 演示數(shù)學(xué)運算
    print("數(shù)學(xué)運算:")
    print(f"2 + 3 = {add(2, 3)}")
    print(f"5 - 3 = {sub(5, 3)}")
    print(f"2 * 3 = {mult(2, 3)}")
    print(f"6 / 3 = {div(6, 3)}")
    print("\n" + "="*40 + "\n")
    
    # 演示錯誤處理
    print("錯誤處理:")
    try:
        result = divide(5, 0)
        print(f"5 / 0 = {result}")
    except ZeroDivisionError as e:
        print(f"錯誤: {e}")

if __name__ == "__main__":
    main()

5、(關(guān)鍵)配置打包信息

pyproject.toml 和 setup.py 都是用于配置和打包 Python 項目的工具,但它們代表了不同的打包標(biāo)準(zhǔn)和時代。主要區(qū)別如下:

特性setup.pypyproject.toml
出現(xiàn)時間早期(distutils/setuptools 時代)較新(PEP 518 及以后)
格式Python 腳本TOML 配置文件
可執(zhí)行性可執(zhí)行代碼,靈活性高但易濫用聲明式配置,更安全
依賴管理通常寫在 setup.py 或 requirements.txt 中可直接在 pyproject.toml 中聲明依賴
構(gòu)建系統(tǒng)指定默認(rèn)使用 setuptools顯式指定構(gòu)建后端(如 setuptools, poetry, flit 等)
標(biāo)準(zhǔn)支持傳統(tǒng)方式,逐漸被替代當(dāng)前推薦方式(現(xiàn)代 Python 打包標(biāo)準(zhǔn))

方式一:使用 pyproject.toml(推薦方式)

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

[project]
name = "simple-math"
version = "0.1.0"
description = "一個簡單的數(shù)學(xué)計算"
readme = "README.md"
requires-python = ">=3.8"
license = {text = "MIT"}
authors = [
    {name = "your_name", email = "your.email@example.com"}
]
keywords = ["math", "calculator", "hello-world", "example"]
classifiers = [
    "Development Status :: 3 - Alpha",
    "Intended Audience :: Education",
    "Intended Audience :: Developers",
    "License :: OSI Approved :: MIT License",
    "Programming Language :: Python :: 3",
    "Programming Language :: Python :: 3.8",
    "Programming Language :: Python :: 3.9",
    "Programming Language :: Python :: 3.10",
    "Programming Language :: Python :: 3.11",
    "Topic :: Education",
    "Topic :: Software Development :: Libraries :: Python Modules",
]

dependencies = []

[project.urls]
Homepage = "https://github.com/yourusername/simple-math"
Documentation = "https://github.com/yourusername/simple-math#readme"
Repository = "https://github.com/yourusername/simple-math"
Issues = "https://github.com/yourusername/simple-math"

[tool.setuptools]
package-dir = {"" = "src"}

[tool.setuptools.packages.find]
where = ["src"]

# 配置測試命令
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-v"

方式二:傳統(tǒng)的 setup.py 方式(可選)

from setuptools import setup, find_packages

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

setup(
    name="simple-math",
    version="0.1.0",
    author="your_name",
    author_email="your.email@example.com",
    description="一個簡單的數(shù)學(xué)計算",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/yourusername/simple-math",
    package_dir={"": "src"},
    packages=find_packages(where="src"),
    classifiers=[
        "Development Status :: 3 - Alpha",
        "Intended Audience :: Education",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.8",
        "Programming Language :: Python :: 3.9",
        "Programming Language :: Python :: 3.10",
        "Programming Language :: Python :: 3.11",
        "Topic :: Education",
        "Topic :: Software Development :: Libraries :: Python Modules",
    ],
    python_requires=">=3.8",
    install_requires=[],
    extras_require={
        "dev": ["pytest>=7.0", "twine>=4.0"],
    },
)

6、編寫文檔和許可文件

  • README.md

創(chuàng)建一個詳細(xì)的 README 文件:

# 簡單數(shù)學(xué)計算包 (simple-math)
一個簡單的Python包,提供基本的數(shù)學(xué)運算。

## 功能
- **加法**: 將兩個數(shù)字相加
- **減法**: 從第一個數(shù)字中減去第二個數(shù)字
- **乘法**: 將兩個數(shù)字相乘
- **除法**: 將第一個數(shù)字除以第二個數(shù)字(含錯誤處理)

## 安裝
pip install simple-math
  • LICENSE文件

選擇一個合適的開源許可證,如MIT:

MIT License

Copyright (c) 2023 <your_name>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

7、構(gòu)建 Wheel 包

現(xiàn)在一切準(zhǔn)備就緒,可以構(gòu)建 wheel 包了。

# 確保你在項目根目錄(有pyproject.toml的目錄)
cd simple_math

# 使用現(xiàn)代構(gòu)建工具(推薦)
python -m build --wheel

# 或者使用傳統(tǒng)方式
python setup.py bdist_wheel

8、本地安裝和運行測試

# 安裝wheel包
pip install dist/simple_math-0.1.0-py3-none-any.whl

# 測試安裝是否成功
python -c "import simple_math; print(simple_math.__version__)"

# 運行測試
pip install pytest
pytest

安裝:pip install  <模塊名>

卸載:pip uninstall <模塊名>

結(jié)果:

四、擴(kuò)展:發(fā)布到 PyPI

1、創(chuàng)建 PyPI 賬戶

首先,在 PyPI 和 TestPyPI 上注冊賬戶。

2、安裝 twine

pip install twine

3、上傳到 TestPyPI

twine upload --repository-url https://test.pypi.org/legacy/ dist/*

4、從 TestPyPI 安裝測試

pip install --index-url https://test.pypi.org/simple/ simple-math

5、上傳到正式 PyPI

twine upload dist/*

參考

 到此這篇關(guān)于python中whl文件封裝的實現(xiàn)示例的文章就介紹到這了,更多相關(guān)python whl文件封裝內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 在PyCharm中遇到pip安裝 失敗問題及解決方案(pip失效時的解決方案)

    在PyCharm中遇到pip安裝 失敗問題及解決方案(pip失效時的解決方案)

    這篇文章主要介紹了在PyCharm中遇到pip安裝失敗問題及解決方案(pip失效時的解決方案),本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-03-03
  • 基于Python的ModbusTCP客戶端實現(xiàn)詳解

    基于Python的ModbusTCP客戶端實現(xiàn)詳解

    這篇文章主要介紹了基于Python的ModbusTCP客戶端實現(xiàn)詳解,Modbus Poll和Modbus Slave是兩款非常流行的Modbus設(shè)備仿真軟件,支持Modbus RTU/ASCII和Modbus TCP/IP協(xié)議 ,經(jīng)常用于測試和調(diào)試Modbus設(shè)備,觀察Modbus通信過程中的各種報文,需要的朋友可以參考下
    2019-07-07
  • OpenCV-Python?對圖像的基本操作代碼

    OpenCV-Python?對圖像的基本操作代碼

    這篇文章主要介紹了OpenCV-Python?對圖像的基本操作,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-11-11
  • python接口自動化之正則用例參數(shù)化的示例詳解

    python接口自動化之正則用例參數(shù)化的示例詳解

    這篇文章主要介紹了python接口自動化之正則用例參數(shù)化,它是一個特殊的字符序列,它能幫助你方便的檢查一個字符串是否與某種模式匹配,本文給大家介紹的非常詳細(xì),需要的朋友可以參考下
    2022-07-07
  • Python線程條件變量Condition原理解析

    Python線程條件變量Condition原理解析

    這篇文章主要介紹了Python線程條件變量Condition原理解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-01-01
  • python免殺技術(shù)shellcode的加載與執(zhí)行

    python免殺技術(shù)shellcode的加載與執(zhí)行

    本文主要介紹了python免殺技術(shù)shellcode的加載與執(zhí)行,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-04-04
  • Python實現(xiàn)將Excel轉(zhuǎn)換為json的方法示例

    Python實現(xiàn)將Excel轉(zhuǎn)換為json的方法示例

    這篇文章主要介紹了Python實現(xiàn)將Excel轉(zhuǎn)換為json的方法,涉及Python文件讀寫及格式轉(zhuǎn)換相關(guān)操作技巧,需要的朋友可以參考下
    2017-08-08
  • 詳解Django中的unittest及應(yīng)用

    詳解Django中的unittest及應(yīng)用

    unittest是python的一個單元測試框架,它是用于對一個確定結(jié)果和預(yù)測結(jié)果的一種判斷,這篇文章主要介紹了Django中的unittest及應(yīng)用,需要的朋友可以參考下
    2021-11-11
  • Python辦公自動化之網(wǎng)絡(luò)監(jiān)控和壓縮文件處理

    Python辦公自動化之網(wǎng)絡(luò)監(jiān)控和壓縮文件處理

    Python辦公?動化是利用Python編程語?來創(chuàng)建腳本和程序,以簡化、加速和?動化?常辦公任務(wù)和工作流程的過程,本文主要介紹了如何進(jìn)行網(wǎng)絡(luò)監(jiān)控和壓縮文件處理,感興趣的可以了解下
    2023-12-12
  • Python 強(qiáng)大的信號庫 blinker 入門詳細(xì)教程

    Python 強(qiáng)大的信號庫 blinker 入門詳細(xì)教程

    這篇文章主要介紹了Python 強(qiáng)大的信號庫 blinker 入門教程,信號的特點就是發(fā)送端通知訂閱者發(fā)生了什么,使用信號分為 3 步:定義信號,監(jiān)聽信號,發(fā)送信號,需要的朋友可以參考下
    2022-02-02

最新評論