search
HomeBackend DevelopmentPython TutorialExplore the use of Python packages

探索 Python 包的使用

Python packages allow you to break up large systems and organize their modules in a consistent way so that you and others can use and reuse them efficiently. Python's motto "battery built in" means that it comes pre-installed with many useful packages in the standard library.

But you can also take advantage of many amazing third-party software packages. In this tutorial, you'll learn everything you need to know about what exactly a package is, how to import modules from a package, explore the built-in packages in the Python standard library, and install third-party packages.

What is a package?

Before discussing packages, let’s discuss modules first. A module is a source file with *.py extension where you (and others) place the functions and classes that make up your program.

A package in Python is just a folder containing multiple Python files, and there should be an __init__.py file. The __init__.py file indicates that the directory is a package. __init__.py The file can be empty or contain some executable code.

Package is the embodiment of Python's hierarchical namespace concept. Quoting the Zen of Python:

"Namespaces are a great idea - let's do more of them!"

To view the entire Python Zen, enter import this:

in a Python interactive session
>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
>>> 

Namespaces help organize code and prevent naming conflicts. This is crucial when multiple people are working together or using packages developed by others.

While a package represents a hierarchy of subpackages and modules (which are files), the hierarchy does not have to be based on a file system, where packages and subpackages are directories and subdirectories. It's much more flexible than that.

Create Python package

Let's start with a simple example. Below we have a package called simple_package which contains two Python modules.

simple_package
.
├── __init__.py
├── tasks.py
└── views.py

0 directories, 3 files
  • __init__.py: Indicates that it is a package
  • tasks.py and views.py are modules

Third Party Software Package

Let’s take a look at the package named ansible. It is not a package in the standard library. You'll see later how to find and install third-party packages. Now, let's take a look at the directory file structure.

These packages are typically installed into the Python interpreter's site-packages directory, somewhere under lib (depending on version, operating system, and distribution).

For example, on a Mac, Python 3.10 would be located in /lib/python3.10/site-packages. Here's how ansible packages are organized:

tree ansible -L 1
ansible
├── cli
├── collections
├── compat
├── config
├── constants.py
├── context.py
├── errors
├── executor
├── galaxy
├── __init__.py
├── inventory
├── keyword_desc.yml
├── __main__.py
├── modules
├── module_utils
├── parsing
├── playbook
├── plugins
├── __pycache__
├── release.py
├── template
├── utils
├── vars
└── _vendor

18 directories, 6 files

There are 6 modules and 18 directories. Each directory is a sub-package of the main ansible package. Looking at the ansible/utils directory, we can see that it contains other modules and even a sub-package:

tree ansible/utils -L 1
ansible/utils
├── cmd_functions.py
├── collection_loader
├── color.py
├── context_objects.py
├── display.py
├── encrypt.py
├── fqcn.py
├── galaxy.py
├── hashing.py
├── helpers.py
├── __init__.py
├── jsonrpc.py
├── _junit_xml.py
├── listify.py
├── lock.py
├── multiprocessing.py
├── native_jinja.py
├── path.py
├── plugin_docs.py
├── py3compat.py
├── sentinel.py
├── shlex.py
├── singleton.py
├── ssh_functions.py
├── unicode.py
├── unsafe_proxy.py
├── vars.py
└── version.py

1 directory, 27 files

Search path

When you import a module, Python will perform a search algorithm based on the search path, which is the list of directories to start searching. The search path is a list of directories available through sys.path, and you can dynamically manipulate it (add, delete, or move items in the search path). The site-packages directory always exists.

To import the path.py module from ansible/utils you need to use the following command:

import ansible.utils.path

To import the path and encrypt modules, use the following command:

import ansible.utils.path
import ansible.utils.encrypt

If you also want to use the standard os.path module, you would use the following command:

import os.path

Now you can use one or both of the path modules without conflicting due to the namespace they belong to.

Exploring the Standard Library

The standard library has many packages. Whenever you need to complete a task but aren't sure how, it's worth exploring it. For any common task, such as math, shell integration, operating system integration, string manipulation, networking, and common file formats, there is most likely a well-designed, well-performing, and well-tested package in the standard library.

You can really trust the standard library packages, because getting into the standard library is a big deal. The package was either designed by core Python developers or was heavily vetted and used heavily in the field as a third-party library before making it into the standard library.

The following are all packages in the standard library organized by topic.

PyPI

The standard library is great, but often there are special features you need that are not standard. This doesn't mean you have to write it from scratch. Python has a vibrant and active community that develops and shares large amounts of code for free. Enter PyPI: The Python Package Index. PyPI hosts all publicly available software packages and provides a one-stop shop for browsing them.

浏览 PyPI

PyPI 将包组织在可浏览的索引中。您可以按主题、环境、框架、开发、状态、目标受众、许可证、自然语言、编程语言(是的,有支持多种编程语言的 Python 包)和操作系统来浏览和搜索。

截至 2021 年,PyPI 不再显示软件包的下载统计信息,因为维护统计信息所需的资源导致其效率低下。

安装软件包

有两种方法可以从 PyPI 安装软件包。您可以下载该软件包,然后运行 ​​python setup.py install。但现代的方法是使用 pip、setuptools 和wheel。

从 Python 3.4 和 Python 2.79 开始默认包含 Pip 和 setuptools,但您需要升级到最新版本:

  • Linux/macOS:pip install -U pip setuptools
  • Windows:python -m pip install -U pip setuptools
但是,不再支持 Python 2,因此您应该已经使用 Python 3.0 或更高版本来提高性能。

使用pip安装wheel:

pip install wheel.

要使用 pip 安装软件包,请发出此命令。

pip install <package_name>

其中 package_name 是包的名称。例如,要安装 Ansible,命令如下所示:

pip install ansible

如果需要特定版本,也可以指定如下:

pip install ansible==7.0

Python 包始终安装到环境中。我在这里不会介绍的一种常见做法是使用虚拟环境来管理具有不同解释器和/或不同安装包集的多个独立的 Python 安装。您可以在此处阅读有关虚拟环境的更多信息。

最佳实践

Python 打包权威提供了大量有关打包最佳实践的指导。这很重要,因为这是一个正在积极开发的领域,并且建议会快速发展。

此外,如果您想做一些特别的事情,例如从替代存储库而不是 PyPI 安装软件包或以更复杂的方式使用 pip,您会发现精彩的讨论和实用的建议。

结论

当您是 Python 初学者时,您会学习核心语言并享受使用它的乐趣。很快您就会发现标准库,并且随着您获得更多经验,您会从它的丰富性中受益越来越多。

作为 Pythonista,您发展的下一阶段是将 Python 社区在 PyPI 上带来的巨大优势融入到您的系统中。包作为可重用 Python 代码的部署单元使这个生态系统得以实现。

The above is the detailed content of Explore the use of Python packages. For more information, please follow other related articles on the PHP Chinese website!

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
Are Python lists dynamic arrays or linked lists under the hood?Are Python lists dynamic arrays or linked lists under the hood?May 07, 2025 am 12:16 AM

Pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)Theyarestoredincontiguousmemoryblocks,whichmayrequirereallocationwhenappendingitems,impactingperformance.2)Linkedlistswouldofferefficientinsertions/deletionsbutslowerindexedaccess,leadingPytho

How do you remove elements from a Python list?How do you remove elements from a Python list?May 07, 2025 am 12:15 AM

Pythonoffersfourmainmethodstoremoveelementsfromalist:1)remove(value)removesthefirstoccurrenceofavalue,2)pop(index)removesandreturnsanelementataspecifiedindex,3)delstatementremoveselementsbyindexorslice,and4)clear()removesallitemsfromthelist.Eachmetho

What should you check if you get a 'Permission denied' error when trying to run a script?What should you check if you get a 'Permission denied' error when trying to run a script?May 07, 2025 am 12:12 AM

Toresolvea"Permissiondenied"errorwhenrunningascript,followthesesteps:1)Checkandadjustthescript'spermissionsusingchmod xmyscript.shtomakeitexecutable.2)Ensurethescriptislocatedinadirectorywhereyouhavewritepermissions,suchasyourhomedirectory.

How are arrays used in image processing with Python?How are arrays used in image processing with Python?May 07, 2025 am 12:04 AM

ArraysarecrucialinPythonimageprocessingastheyenableefficientmanipulationandanalysisofimagedata.1)ImagesareconvertedtoNumPyarrays,withgrayscaleimagesas2Darraysandcolorimagesas3Darrays.2)Arraysallowforvectorizedoperations,enablingfastadjustmentslikebri

For what types of operations are arrays significantly faster than lists?For what types of operations are arrays significantly faster than lists?May 07, 2025 am 12:01 AM

Arraysaresignificantlyfasterthanlistsforoperationsbenefitingfromdirectmemoryaccessandfixed-sizestructures.1)Accessingelements:Arraysprovideconstant-timeaccessduetocontiguousmemorystorage.2)Iteration:Arraysleveragecachelocalityforfasteriteration.3)Mem

Explain the performance differences in element-wise operations between lists and arrays.Explain the performance differences in element-wise operations between lists and arrays.May 06, 2025 am 12:15 AM

Arraysarebetterforelement-wiseoperationsduetofasteraccessandoptimizedimplementations.1)Arrayshavecontiguousmemoryfordirectaccess,enhancingperformance.2)Listsareflexiblebutslowerduetopotentialdynamicresizing.3)Forlargedatasets,arrays,especiallywithlib

How can you perform mathematical operations on entire NumPy arrays efficiently?How can you perform mathematical operations on entire NumPy arrays efficiently?May 06, 2025 am 12:15 AM

Mathematical operations of the entire array in NumPy can be efficiently implemented through vectorized operations. 1) Use simple operators such as addition (arr 2) to perform operations on arrays. 2) NumPy uses the underlying C language library, which improves the computing speed. 3) You can perform complex operations such as multiplication, division, and exponents. 4) Pay attention to broadcast operations to ensure that the array shape is compatible. 5) Using NumPy functions such as np.sum() can significantly improve performance.

How do you insert elements into a Python array?How do you insert elements into a Python array?May 06, 2025 am 12:14 AM

In Python, there are two main methods for inserting elements into a list: 1) Using the insert(index, value) method, you can insert elements at the specified index, but inserting at the beginning of a large list is inefficient; 2) Using the append(value) method, add elements at the end of the list, which is highly efficient. For large lists, it is recommended to use append() or consider using deque or NumPy arrays to optimize performance.

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

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool