python程序打包分发

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

python程序打包分发

JeremyL   2022-09-08 我要评论

引言

python编程时,一部分人习惯将实现同一个功能的代码放在同一个文件;

使用这些代码只需要import就可以了;

下面看一个例子。

testModel.py

class Test:
    name = 'tom'
    age = 0
    __weight = 0
    def __init__(self,n,a,w):
        self.name = n
        self.age = a
        self.__weight = w
    def speak(self):
        print("Test model: ",self.name,self.age, self.__weight)

接着,引用上面的代码:

import testModel
testModel.Test("tom", 0, 1).speak()
# Test model:  tom 0 1

python程序打包

  • 新建一个文件夹testPackages;
  • testPackages下新建一个空文件__init__.py,声明这是一个python包
  • testPackages下新建一个空文件testModel.py,用于存放函数代码
testPackages/
        ├── __init__.py
        └── testModel.py

接着,引用上面的代码:

from testPackages import testModel
testModel.Test("tom", 0, 1).speak()
# Test model:  tom 0 1

 __init__.py文件的作用

__init__.py的作用就是申明这是一个包;

每次导入包之前都会先执行__init__.py,因此可以在其中申明一些定义,比如变量或接口;

下面我们看一个__init__.py的使用例子

testPackages/
        ├── __init__.py
        ├── add.py
        └── testModel.py

add.py

def add(a, b):
    return a + b

__init__.py

import testPackages.add
add = testPackages.add.add

接着,引用上面的代码:

import testPackages
testPackages.add(1,2)
# 3

构建python包

使用setuptools构建python包

packaging_tutorial/
├── LICENSE
├── pyproject.toml  #使用什么工具(pip或build)构建项目
├── README.md
├── src/
│   └── example_package/
│       ├── __init__.py
│       └── example.py
└── tests/  #例子数据

pyproject.toml

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

setup.py是setuptool的构建脚本,用于设置包的基本信息:名字,版本和源码地址

import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
    long_description = fh.read()
setuptools.setup(
    name="testPackages",
    version="2.2.1",
    author="Author",
    author_email="author@example.com",
    description="A small example package",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="http://baidu.com/",
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
    package_dir={"": "src"},
    packages=setuptools.find_packages(where="src"),
    python_requires=">=3.6",
)

setup()参数:

package_dir:字典,key是包名,value是一个文件夹;

packages:分发包需要导入的所有模块列表;可以手动输入,也可以使用find_packages函数自动寻找package_dir下的所有包或模块。

生成分发包

python3 setup.py sdist

本地安装

python3 -m pip install ./dist/testPackages-2.2.1.tar.gz

调用

from testPackages import add
add.add(1,2)
# 3
#在__init__.py构建了add = testPackages.add.add,所以可以直接使用
add(1,2)
# 3

参考 Packaging Python Projects

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们