日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

python程序的打包分發示例詳解_python

作者:JeremyL ? 更新時間: 2022-08-20 編程語言

引言

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

原文鏈接:https://www.jianshu.com/p/93380d107781

欄目分類
最近更新