python中whl文件封装的实现示例

 更新时间:2025年08月24日 08:38:55   作者:青铜发条  
Wheel(.whl)是 Python 的一种内置包格式,本文就来介绍一下python中whl文件封装的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

一、Whl 包简介

Wheel(.whl)是 Python 的一种内置包格式,用于替代传统的 egg 格式。它被设计为更快速安装的替代方案,具有以下优点:

  • 安装速度快:预编译格式,无需在安装时执行 setup.py
  • 更可靠:避免了执行任意代码的风险
  • 支持二进制分发:可以包含编译的扩展文件
  • 现代标准:是当前 Python 包分发的推荐格式

二、准备工具包

制作whl包需要依赖相应的工具包,安装方法如下:

pip install setuptools wheel twine
  • setuptools:用来打包你的项目,定义项目信息(名字、版本、依赖等)并生成分发文件(如 .whl 或 .tar.gz)。
  • wheel:一种高效的包格式(.whl 文件),安装快、无需编译,setuptools 用它来生成这种包。
  • twine:安全地将打包好的文件(.whl 或 .tar.gz)上传到 PyPI 或私有仓库。

三、详细制作流程

为了方便演示,创建了一个加减乘除的方法例子来演示。

1、创建目录结构

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:
    """
    将两个数字相加
    
    Args:
        a (float): 第一个数字
        b (float): 第二个数字
        
    Returns:
        float: 两个数字的和
    """
    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:
    """
    将第一个数字除以第二个数字
    
    Args:
        a (float): 被除数
        b (float): 除数
        
    Returns:
        float: 两个数字的商
        
    Raises:
        ZeroDivisionError: 当除数为零时抛出
    """
    if b == 0:
        raise ZeroDivisionError("除数不能为零")
    return float(a / b)
  • src/simple_math/__init__.py文件:
"""
简单数学计算包
提供加减乘除基本运算
"""

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

# 导入所有功能,方便用户直接使用
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、(可选)创建示例使用代码

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

def main():
    """演示所有功能的使用"""
    print("=== math_ops 包使用示例 ===\n")
    
    # 演示数学运算
    print("数学运算:")
    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、(关键)配置打包信息

pyproject.toml 和 setup.py 都是用于配置和打包 Python 项目的工具,但它们代表了不同的打包标准和时代。主要区别如下:

特性setup.pypyproject.toml
出现时间早期(distutils/setuptools 时代)较新(PEP 518 及以后)
格式Python 脚本TOML 配置文件
可执行性可执行代码,灵活性高但易滥用声明式配置,更安全
依赖管理通常写在 setup.py 或 requirements.txt 中可直接在 pyproject.toml 中声明依赖
构建系统指定默认使用 setuptools显式指定构建后端(如 setuptools, poetry, flit 等)
标准支持传统方式,逐渐被替代当前推荐方式(现代 Python 打包标准)

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

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

[project]
name = "simple-math"
version = "0.1.0"
description = "一个简单的数学计算"
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"

方式二:传统的 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="一个简单的数学计算",
    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

创建一个详细的 README 文件:

# 简单数学计算包 (simple-math)
一个简单的Python包,提供基本的数学运算。

## 功能
- **加法**: 将两个数字相加
- **减法**: 从第一个数字中减去第二个数字
- **乘法**: 将两个数字相乘
- **除法**: 将第一个数字除以第二个数字(含错误处理)

## 安装
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、构建 Wheel 包

现在一切准备就绪,可以构建 wheel 包了。

# 确保你在项目根目录(有pyproject.toml的目录)
cd simple_math

# 使用现代构建工具(推荐)
python -m build --wheel

# 或者使用传统方式
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 <模块名>

结果:

四、扩展:发布到 PyPI

1、创建 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/*

参考

 到此这篇关于python中whl文件封装的实现示例的文章就介绍到这了,更多相关python whl文件封装内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 在PyCharm中遇到pip安装 失败问题及解决方案(pip失效时的解决方案)

    在PyCharm中遇到pip安装 失败问题及解决方案(pip失效时的解决方案)

    这篇文章主要介绍了在PyCharm中遇到pip安装失败问题及解决方案(pip失效时的解决方案),本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-03-03
  • 基于Python的ModbusTCP客户端实现详解

    基于Python的ModbusTCP客户端实现详解

    这篇文章主要介绍了基于Python的ModbusTCP客户端实现详解,Modbus Poll和Modbus Slave是两款非常流行的Modbus设备仿真软件,支持Modbus RTU/ASCII和Modbus TCP/IP协议 ,经常用于测试和调试Modbus设备,观察Modbus通信过程中的各种报文,需要的朋友可以参考下
    2019-07-07
  • OpenCV-Python 对图像的基本操作代码

    OpenCV-Python 对图像的基本操作代码

    这篇文章主要介绍了OpenCV-Python 对图像的基本操作,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-11-11
  • python接口自动化之正则用例参数化的示例详解

    python接口自动化之正则用例参数化的示例详解

    这篇文章主要介绍了python接口自动化之正则用例参数化,它是一个特殊的字符序列,它能帮助你方便的检查一个字符串是否与某种模式匹配,本文给大家介绍的非常详细,需要的朋友可以参考下
    2022-07-07
  • Python线程条件变量Condition原理解析

    Python线程条件变量Condition原理解析

    这篇文章主要介绍了Python线程条件变量Condition原理解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-01-01
  • python免杀技术shellcode的加载与执行

    python免杀技术shellcode的加载与执行

    本文主要介绍了python免杀技术shellcode的加载与执行,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-04-04
  • Python实现将Excel转换为json的方法示例

    Python实现将Excel转换为json的方法示例

    这篇文章主要介绍了Python实现将Excel转换为json的方法,涉及Python文件读写及格式转换相关操作技巧,需要的朋友可以参考下
    2017-08-08
  • 详解Django中的unittest及应用

    详解Django中的unittest及应用

    unittest是python的一个单元测试框架,它是用于对一个确定结果和预测结果的一种判断,这篇文章主要介绍了Django中的unittest及应用,需要的朋友可以参考下
    2021-11-11
  • Python办公自动化之网络监控和压缩文件处理

    Python办公自动化之网络监控和压缩文件处理

    Python办公⾃动化是利用Python编程语⾔来创建脚本和程序,以简化、加速和⾃动化⽇常办公任务和工作流程的过程,本文主要介绍了如何进行网络监控和压缩文件处理,感兴趣的可以了解下
    2023-12-12
  • Python 强大的信号库 blinker 入门详细教程

    Python 强大的信号库 blinker 入门详细教程

    这篇文章主要介绍了Python 强大的信号库 blinker 入门教程,信号的特点就是发送端通知订阅者发生了什么,使用信号分为 3 步:定义信号,监听信号,发送信号,需要的朋友可以参考下
    2022-02-02

最新评论