search
HomeBackend DevelopmentPython Tutorial解析Python编程中的包结构

假设你想设计一个模块集(也就是一个“包”)来统一处理声音文件和声音数据。通常由它们的扩展有不同的声音格式,例如:WAV,AIFF,AU),所以你可能需要创建和维护一个不断增长的各种文件格式之间的转换的模块集合。并且可能要执行声音数据处理(如混合,添加回声,应用平衡功能),所以你写一个永无止境的流模块来执行这些操作:模块设计的包如下:

sound/             Top-level package
   __init__.py        Initialize the sound package
   formats/         Subpackage for file format conversions
       __init__.py
       wavread.py
       wavwrite.py
       aiffread.py
       aiffwrite.py
       auread.py
       auwrite.py
       ...
   effects/         Subpackage for sound effects
       __init__.py
       echo.py
       surround.py
       reverse.py
       ...
   filters/         Subpackage for filters
       __init__.py
       equalizer.py
       vocoder.py
       karaoke.py
       ...

当导入包以后,Python通过sys.path中的目录来寻找包的子目录。 每一个包都必须有__init__.py文件,这样做是为了防止某些目录有一个共同的名字。在最简单的情况下,__ init__.py可以只是一个空文件,但它也可以执行包的初始化代码,包括设置__all__变量,稍后介绍。 我们可以从包中导入单个模块,

例如: import sound.effects.echo 这会载入子模块sound.effects.echo。它必须引用全名。

sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)

另外一种导入子模块的方法: from sound.effects import echo 这样就加载了echo子模块,没有包括包的前缀,因此它可以用作如下:

echo.echofilter(input, output, delay=0.7, atten=4)

或者可以

from sound.effects.echo import echofilter echofilter(input, output, delay=0.7, atten=4)

请注意,如果你使用包导入一个子模块(或子包),像一个函数,类或变量。 import语句首先测试导入的对象是否包中定义,如果没有,它假定这是一个模块,并尝试加载它。如果还没有找到,则会引发一个ImportError异常。

python 包管理工具大乱斗
1. distutils

distutils 是 python 标准库的一部分,2000年发布。使用它能够进行 python 模块的 安装 和 发布。

setup.py 就是利用 distutils 的功能写成,我们可以看一个简单的 setup.py 的例子。

在这里可以看到关于 setupt.py 格式的所有详细描述:Writing the Setup Script。

要安装一个模块到当前的 python 环境中,可以使用这个模块提供的 setup.py 文件:

python setup.py install

下面的代码会发布一个 python 模块,将其打包成 tar.gz 或者 zip 压缩包:
python setup.py sdist

甚至能打包成 rpm 或者 exe 安装包:

python setup.py bdist_rpm
python setup.py bdist_wininst

2. setuptools 和 distribute

setuptools 是一个为了增强 distutils 而开发的集合,2004年发布。它包含了 easy_install 这个工具。

ez_setup.py 是 setuptools 的安装工具。ez 就是 easy 的缩写。

简单的说,setuptools 是一个项目的名称,是基础组件。而 easy_install 是这个项目中提供的工具,它依赖基础组件工作。

为了方便描述,下面文章中提到的 setuptools 被认为与 easy_install 同义。

使用 setuptools 可以自动 下载、构建、安装和管理 python 模块。

例如,从 PyPI 上安装一个包:

easy_install SQLObject

下载一个包文件,然后安装它:

easy_install http://example.com/path/to/MyPackage-1.2.3.tgz

从一个 .egg 格式安装:

easy_install /my_downloads/OtherPackage-3.2.1-py2.3.egg

distribute 是 setuptools 的一个分支版本。分支的原因可能是有一部分开发者认为 setuptools 开发太慢了。但现在,distribute 又合并回了 setuptools 中。因此,我们可以认为它们是同一个东西。事实上,如果你查看一下 easy_install 的版本,会发现它本质上就是 distribute 。

# easy_install --version
distribute 0.6.28

3. Eggs

Eggs 格式是 setuptools 引入的一种文件格式,它使用 .egg 扩展名,用于 Python 模块的安装。

setuptools 可以识别这种格式。并解析它,安装它。

4. pip

注意,从此处开始,easy_install 和 setuptools 不再同义。

pip 是目前 python 包管理的事实标准,2008年发布。它被用作 easy_install 的替代品,但是它仍有大量的功能建立在 setuptools 组件之上。

pip 希望不再使用 Eggs 格式(虽然它支持 Eggs),而更希望采用“源码发行版”(使用 python setup.py sdict 创建)。这可以充分利用 Requirements File Format 提供的方便功能。

pip 可以利用 requirments.txt 来实现在依赖的安装。在 setup.py 中,也存在一个 install_requires 表来指定依赖的安装。

pip 支持 git/svn/hg 等流行的 VCS 系统,可以直接从 gz 或者 zip 压缩包安装,支持搜索包,以及指定服务器安装等等功能。

pip vs easy_install 详细介绍了两者的不同。它们可以说是各占胜场,但 pip 明显优势更大。

5. wheel

wheel 本质上是一个 zip 包格式,它使用 .whl 扩展名,用于 python 模块的安装,它的出现是为了替代 Eggs。

wheel 还提供了一个 bdist_wheel 作为 setuptools 的扩展命令,这个命令可以用来生成 wheel 包。

pip 提供了一个 wheel 子命令来安装 wheel 包。当然,需要先安装 wheel 模块。

setup.cfg 可以用来定义 wheel 打包时候的相关信息。

Wheel vs Egg 详细介绍了 wheel 和 Eggs 格式的区别,很显然,wheel 优势明显。

Python Wheels 网站展示了使用 Wheels 发行的 python 模块在 PyPI 上的占有率。

pypip.in 也支持 wheel。

6. distutils2 和 distlib

distutils2 被设计为 distutils 的替代品。从2009年开发到2012年。它包含更多的功能,并希望以 packaging 作为名称进入 python 3.3 成为标准库的一部分。但这个计划 后来停滞了 。

distlib 是 distutils2 的部分,它为 distutils2/packaging 提供的低级功能增加高级 API,使其便于使用。

这里 介绍了 distlib 没有进入 python 3.3 标准库的一些原因。

因此,可以暂时不必了解这两个工具,静观其变即可。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What are the alternatives to concatenate two lists in Python?What are the alternatives to concatenate two lists in Python?May 09, 2025 am 12:16 AM

There are many methods to connect two lists in Python: 1. Use operators, which are simple but inefficient in large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use the = operator, which is both efficient and readable; 4. Use itertools.chain function, which is memory efficient but requires additional import; 5. Use list parsing, which is elegant but may be too complex. The selection method should be based on the code context and requirements.

Python: Efficient Ways to Merge Two ListsPython: Efficient Ways to Merge Two ListsMay 09, 2025 am 12:15 AM

There are many ways to merge Python lists: 1. Use operators, which are simple but not memory efficient for large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use itertools.chain, which is suitable for large data sets; 4. Use * operator, merge small to medium-sized lists in one line of code; 5. Use numpy.concatenate, which is suitable for large data sets and scenarios with high performance requirements; 6. Use append method, which is suitable for small lists but is inefficient. When selecting a method, you need to consider the list size and application scenarios.

Compiled vs Interpreted Languages: pros and consCompiled vs Interpreted Languages: pros and consMay 09, 2025 am 12:06 AM

Compiledlanguagesofferspeedandsecurity,whileinterpretedlanguagesprovideeaseofuseandportability.1)CompiledlanguageslikeC arefasterandsecurebuthavelongerdevelopmentcyclesandplatformdependency.2)InterpretedlanguageslikePythonareeasiertouseandmoreportab

Python: For and While Loops, the most complete guidePython: For and While Loops, the most complete guideMay 09, 2025 am 12:05 AM

In Python, a for loop is used to traverse iterable objects, and a while loop is used to perform operations repeatedly when the condition is satisfied. 1) For loop example: traverse the list and print the elements. 2) While loop example: guess the number game until you guess it right. Mastering cycle principles and optimization techniques can improve code efficiency and reliability.

Python concatenate lists into a stringPython concatenate lists into a stringMay 09, 2025 am 12:02 AM

To concatenate a list into a string, using the join() method in Python is the best choice. 1) Use the join() method to concatenate the list elements into a string, such as ''.join(my_list). 2) For a list containing numbers, convert map(str, numbers) into a string before concatenating. 3) You can use generator expressions for complex formatting, such as ','.join(f'({fruit})'forfruitinfruits). 4) When processing mixed data types, use map(str, mixed_list) to ensure that all elements can be converted into strings. 5) For large lists, use ''.join(large_li

Python's Hybrid Approach: Compilation and Interpretation CombinedPython's Hybrid Approach: Compilation and Interpretation CombinedMay 08, 2025 am 12:16 AM

Pythonusesahybridapproach,combiningcompilationtobytecodeandinterpretation.1)Codeiscompiledtoplatform-independentbytecode.2)BytecodeisinterpretedbythePythonVirtualMachine,enhancingefficiencyandportability.

Learn the Differences Between Python's 'for' and 'while' LoopsLearn the Differences Between Python's 'for' and 'while' LoopsMay 08, 2025 am 12:11 AM

ThekeydifferencesbetweenPython's"for"and"while"loopsare:1)"For"loopsareidealforiteratingoversequencesorknowniterations,while2)"while"loopsarebetterforcontinuinguntilaconditionismetwithoutpredefinediterations.Un

Python concatenate lists with duplicatesPython concatenate lists with duplicatesMay 08, 2025 am 12:09 AM

In Python, you can connect lists and manage duplicate elements through a variety of methods: 1) Use operators or extend() to retain all duplicate elements; 2) Convert to sets and then return to lists to remove all duplicate elements, but the original order will be lost; 3) Use loops or list comprehensions to combine sets to remove duplicate elements and maintain the original order.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment