python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > python whl文件封装

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

作者:青铜发条

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

一、Whl 包简介

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

二、准备工具包

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

pip install setuptools wheel twine

三、详细制作流程

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

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、编写包代码

def add(a: float, b: float) -> float:
    """
    将两个数字相加
    
    Args:
        a (float): 第一个数字
        b (float): 第二个数字
        
    Returns:
        float: 两个数字的和
    """
    return float(a + b)
def sub(a: float, b: float) -> float:
    return float(a - b)
def mult(a: float, b: float) -> float:
    return float(a * b)
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)
"""
简单数学计算包
提供加减乘除基本运算
"""

__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、(可选)编写测试代码

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 文件:

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

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

## 安装
pip install simple-math

选择一个合适的开源许可证,如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文件封装内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文