您现在的位置是:网站首页> 编程资料编程资料
python程序的打包分发示例详解_python_
2023-05-26
380人已围观
简介 python程序的打包分发示例详解_python_
引言
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
以上就是python程序的打包分发示例详解的详细内容,更多关于python程序打包分发的资料请关注其它相关文章!
您可能感兴趣的文章:
相关内容
- python3 最常用的三种装饰器语法汇总_python_
- pip安装路径修改的详细方法步骤_python_
- Python中range()与np.arange()的具体使用_python_
- python中的函数嵌套和嵌套调用_python_
- python项目中requirements.txt的用法实例教程_python_
- 详解Python中位运算的简单实现_python_
- Python利用memory_profiler查看内存占用情况_python_
- python GUI多行输入文本Text的实现_python_
- 浅谈tensorflow与pytorch的相互转换_python_
- python OpenCV图像金字塔_python_
