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.
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
:
>>> 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.
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
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
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
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.
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.
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 将包组织在可浏览的索引中。您可以按主题、环境、框架、开发、状态、目标受众、许可证、自然语言、编程语言(是的,有支持多种编程语言的 Python 包)和操作系统来浏览和搜索。
截至 2021 年,PyPI 不再显示软件包的下载统计信息,因为维护统计信息所需的资源导致其效率低下。
有两种方法可以从 PyPI 安装软件包。您可以下载该软件包,然后运行 python setup.py install
。但现代的方法是使用 pip、setuptools 和wheel。
从 Python 3.4 和 Python 2.79 开始默认包含 Pip 和 setuptools,但您需要升级到最新版本:
pip install -U pip setuptools
python -m pip install -U pip setuptools
使用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!