python程序打包分發(fā)

# python 程序打包分發(fā)

python編程時(shí),一部分人習(xí)慣將實(shí)現(xiàn)同一個(gè)功能的代碼放在同一個(gè)文件;使用這些代碼只需要import就可以了;下面看一個(gè)例子。

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程序打包

  • 新建一個(gè)文件夾testPackages
  • testPackages下新建一個(gè)空文件__init__.py,聲明這是一個(gè)python包
  • testPackages下新建一個(gè)空文件testModel.py,用于存放函數(shù)代碼
testPackages/
        ├── __init__.py
        └── testModel.py

接著,引用上面的代碼:

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

# __init__.py文件的作用:

__init__.py的作用就是申明這是一個(gè)包;

每次導(dǎo)入包之前都會(huì)先執(zhí)行__init__.py,因此可以在其中申明一些定義,比如變量或接口;

下面我們看一個(gè)__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

# 使用setuptools構(gòu)建python包

packaging_tutorial/
├── LICENSE
├── pyproject.toml  #使用什么工具(pip或build)構(gòu)建項(xiàng)目
├── README.md
├── src/
│   └── example_package/
│       ├── __init__.py
│       └── example.py
└── tests/  #例子數(shù)據(jù)

pyproject.toml

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

setup.pysetuptool的構(gòu)建腳本,用于設(shè)置包的基本信息:名字,版本和源碼地址

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()參數(shù):

package_dir:字典,key是包名,value是一個(gè)文件夾;

packages:分發(fā)包需要導(dǎo)入的所有模塊列表;可以手動(dòng)輸入,也可以使用find_packages函數(shù)自動(dòng)尋找package_dir下的所有包或模塊。

#生成分發(fā)包

python3 setup.py sdist

#本地安裝

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

#調(diào)用

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

#在__init__.py構(gòu)建了add = testPackages.add.add,所以可以直接使用
add(1,2)
# 3

# 參考

Packaging Python Projects

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容