1
2
3
4
5
6
7
作者:李晓辉

联系方式:

1. 微信:Lxh_Chat

2. 邮箱:939958092@qq.com
  1. Python 系列(一) 从零开始认识 Python,入门其实没那么难
  2. Python 系列(二) 学 Python 的第一步,把开发环境搭建好
  3. Python 系列(三) 基础语法避坑指南,缩进、大小写、续行与注释
  4. Python 系列(四) Python 输入输出详解,print()、input() 与常见避坑指南
  5. Python 系列(五) 数值类型与运算符详解,整除、浮点精度与进制转换实战
  6. Python 系列(六) 字符串处理实战,查找、替换、切片与日志分析
  7. Python 系列(七) 类型转换详解,int()、float()、str() 与金额计算避坑
  8. Python 系列(八) Python 流程控制入门,掌握 if、elif 和 else
  9. Python 系列(九) Python 逻辑运算符详解,and、or、not 一篇搞懂
  10. Python 系列(十) while、for 循环实战,彻底搞懂 range、break 与 continue
  11. Python 系列(十一) list、tuple、set、dict,到底该怎么选?
  12. Python 系列(十二) List 列表实战,搞定数据增删改查与批量处理
  13. Python 系列(十三) Tuple 元组实战,搞懂不可变特性与 enumerate() 遍历
  14. Python 系列(十四) Set 集合实战,搞定数据去重与集合运算
  15. Python 系列(十五) Dict 字典详解,掌握快速查找与键值操作
  16. Python 系列(十六) sort() 和 sorted() 详解,掌握数据排序技巧
  17. Python 系列(十七) 自定义函数入门,让重复代码一次编写多次使用
  18. Python 系列(十八) 函数参数详解,搞懂位置参数、关键字参数和默认参数
  19. Python 系列(十九) 从 *args 到 **kwargs,让函数调用更灵活
  20. Python 系列(二十) 变量作用域是什么?一文搞懂 global 和 nonlocal
  21. Python 系列(二十一) 搞懂变量、对象和引用,理解函数参数传递机制
  22. Python 系列(二十二) map() 和 filter() 详解,轻松实现批量数据处理与筛选
  23. Python 系列(二十三) 嵌套函数与 lambda 表达式详解,搞懂作用域与闭包
  24. Python 系列(二十四) 搞懂递归函数,从基线条件到实际应用
  25. Python 系列(二十五) 聊聊模块与 import,让代码告别重复编写
  26. Python 系列(二十六) Python 模块入门,从 import 到模块复用
  27. Python 系列(二十七) Python dir() 函数详解,快速查看模块中的函数与属性
  28. Python 系列(二十八) 不会用 Python 标准库?教你快速查找模块和函数
  29. Python 系列(二十九) 搞懂 Python sys 模块,让脚本更适合自动化运维
  30. Python 系列(三十) 为什么 0.1 + 0.2 不等于 0.3?彻底搞懂 Decimal
  31. Python 系列(三十一) 搞懂 datetime 日期时间,轻松处理时区与时间计算
  32. Python 系列(三十二) 面向对象编程入门,从零理解类、对象、封装与继承

学习 Python 的过程中,我们会逐渐接触越来越多的标准库模块。

比如,想查看磁盘使用率,可以使用 shutil 模块;想读取文件和目录信息,可以使用 pathlib 模块;想处理 JSON 数据,可以使用 json 模块;想获取当前时间,可以使用 datetime 模块。

这些功能不需要我们从零开始编写。Python 标准库已经提供了大量经过验证的工具,我们要做的是找到合适的模块,并学会使用它们。

那么,问题来了:标准库模块这么多,遇到实际需求时,应该如何快速找到合适的模块?

可以从以下几个方面入手。

根据实际需求查找模块

最直接的方法,是先明确自己要解决什么问题,再根据功能查找对应的模块。

例如,假设你是一名 Linux 运维工程师,平时需要编写 Python 脚本处理各种任务。

实际需求可以了解的标准库模块主要用途
查看文件和目录pathlib、os路径处理、目录操作、文件系统交互
查看磁盘使用情况shutil文件操作、磁盘空间查询
读取 JSON 配置文件jsonJSON 数据的解析与序列化
获取当前时间datetime、time日期、时间处理
执行外部命令subprocess启动外部程序、获取命令执行结果
读取命令行参数sys、argparse获取参数、构建命令行接口
访问 HTTP 接口urllib.request发送 HTTP 请求
分析日志文件re、pathlib正则匹配、文件路径处理
统计任务执行耗时time、timeit时间获取、代码执行时间测量
生成随机数random随机数生成、随机抽样

这张表不需要死记硬背。刚开始学习时,只要先建立一个概念:遇到问题,先判断它属于什么类型,再寻找对应的标准库模块。

例如,你希望编写一个脚本,定期检查服务器磁盘空间,并在使用率超过 80% 时发出告警。

这时可以先考虑 shutil 模块,因为它提供了查询磁盘使用情况的 disk_usage() 函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import shutil

usage = shutil.disk_usage("/")

total = usage.total
used = usage.used
free = usage.free

percent = used / total * 100

print(f"磁盘总容量:{total / 1024**3:.2f} GiB")
print(f"磁盘已使用:{used / 1024**3:.2f} GiB")
print(f"磁盘使用率:{percent:.2f}%")

if percent > 80:
print("警告:磁盘使用率超过 80%!")

输出

1
2
3
磁盘总容量:200.00 GiB
磁盘已使用:65.56 GiB
磁盘使用率:32.78%

这段代码通过 shutil.disk_usage("/") 获取指定路径所在文件系统的使用情况,然后计算使用率,并根据阈值输出告警。

需要注意,disk_usage() 返回的是指定路径所在文件系统的空间信息,并不是对系统中所有磁盘逐一进行检查。如果要检查多块磁盘或多个挂载点,还需要进一步遍历相应路径。

通过这个例子可以看到,找到合适的模块之后,我们就能直接利用现有功能解决问题,而不必自己编写底层的磁盘查询逻辑。

使用 help() 查看模块信息

前面我们已经学习过 help() 函数。除了查看单个函数的帮助信息,它还可以帮助我们了解模块的功能。

例如,我们想了解 shutil 模块,可以先进入 Python 交互式环境:

1
python3

然后执行:

1
2
>>> import shutil
>>> help(shutil)

Python 会显示 shutil 模块的帮助信息,其中通常包括模块说明、函数、类以及相关对象的文档。

输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
Help on module shutil:

NAME
shutil - Utility functions for copying and archiving files and directory trees.

MODULE REFERENCE
https://docs.python.org/3.15/library/shutil#module-shutil

The following documentation is automatically generated from the Python
source files. It may be incomplete, incorrect or include features that
are considered implementation detail and may vary between Python
implementations. When in doubt, consult the module reference at the
location listed above.

DESCRIPTION
XXX The functions here don't copy the resource fork or other metadata on Mac.

CLASSES
builtins.OSError(builtins.Exception)
Error
SameFileError
SpecialFileError

class Error(builtins.OSError)
| Method resolution order:
| Error
| builtins.OSError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data descriptors defined here:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.OSError:
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __reduce__(self, /)
| Helper for pickle.
|
| __str__(self, /)
| Return str(self).

由于模块内容可能比较多,输出信息也会比较长。阅读时不必从头到尾全部记住,可以优先关注以下内容:

  • 模块的用途是什么。
  • 模块提供了哪些函数和类。
  • 哪些函数与当前需求有关。
  • 函数需要接收什么参数。
  • 函数会返回什么结果,以及可能抛出哪些异常。

例如,我们只想了解 disk_usage() 的用法,就不必阅读整个模块的文档,可以直接执行:

1
>>> help(shutil.disk_usage)

帮助信息会介绍函数的参数和返回值。对于当前的磁盘检查任务,我们重点关注它接收的路径参数,以及返回的 total、used 和 free 三个属性。

1
2
3
4
5
6
7
Help on function disk_usage in module shutil:

disk_usage(path)
Return disk usage statistics about the given path.

Returned values is a named tuple with attributes 'total', 'used' and
'free', which are the amount of total, used and free space, in bytes.

如果只想快速查看模块有哪些名称,也可以使用之前学习过的 dir():

1
>>> dir(shutil)

返回结果中会包含模块中的许多名称,例如:

1
2
3
['SameFileError', 'copy', 'copy2', 'copyfile',
'disk_usage', 'get_archive_formats', 'make_archive',
'move', 'rmtree', ...]

这里的输出只是示意,实际结果会因 Python 版本等因素有所不同。

需要注意,dir(shutil) 展示的是模块中可见的名称,其中既有函数,也可能有类、常量和其他属性。它并不代表这些名称都可以直接调用。

如果发现某个名称看起来与自己的需求有关,可以继续使用 help() 查看它的详细说明。

例如:

1
>>> help(shutil.copy2)

输出

1
2
3
4
5
6
7
8
9
10
11
12
Help on function copy2 in module shutil:

copy2(src, dst, *, follow_symlinks=True)
Copy data and metadata. Return the file's destination.

Metadata is copied with copystat(). Please see the copystat function
for more information.

The destination may be a directory.

If follow_symlinks is false, symlinks won't be followed. This
resembles GNU's "cp -P src dst".

这样就形成了一个简单的探索流程:

flowchart LR
    A["明确要解决的问题"] --> B["找到可能相关的模块"]
    B --> C["import 导入模块"]
    C --> D["使用 dir() 查看名称"]
    D --> E["筛选可能有用的函数"]
    E --> F["使用 help() 查看说明"]
    F --> G["编写代码并验证结果"]

这种方法尤其适合刚接触 Python 的同学。即使暂时记不住函数名称,也可以通过模块探索和帮助信息逐步找到需要的功能。

使用 help(“modules”) 查看模块列表

如果暂时不知道应该使用哪个模块,还可以尝试在 Python 交互式环境中执行:

1
>>> help("modules")

在支持该功能的标准 Python 环境中,它会尝试列出当前环境中可以发现的模块。

输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
Please wait a moment while I gather a list of all available modules...

warning: The `fitz` API is deprecated and will be removed in future. Use `import pymupdf` instead.
__future__ _suggestions extract_pdf pyclbr
__hello__ _symtable extract_tj pydoc
__phello__ _sysconfig faulthandler pydoc_data
_abc _testbuffer filecmp pyexpat
_aix_support _testcapi fileinput pymupdf
_android_support _testclinic fitz queue
_apple_support _testclinic_limited fnmatch quopri
_ast _testconsole fractions random
_ast_unparse _testimportmultiple ftplib re
_asyncio _testinternalcapi functools reprlib
_bisect _testlimitedcapi gc requests
_blake2 _testmultiphase genericpath rlcompleter
_bz2 _testsinglephase getopt runpy
_codecs _thread getpass sched
_codecs_cn _threading_local gettext search_python
_codecs_hk _tkinter glob secrets
_codecs_iso2022 _tokenize graphlib select
_codecs_jp _tracemalloc gzip selectors
_codecs_kr _types hashlib server_check
_codecs_tw _typing heapq shelve
_collections _uuid hmac shlex
_collections_abc _warnings html shutil
_colorize _weakref http signal
_compat_pickle _weakrefset idlelib site
_contextvars _winapi idna smtplib
_csv _wmi imaplib socket
_ctypes _zoneinfo import server_check socketserver
_ctypes_test _zstd importlib sqlite3
_datetime abc inspect ssl
_decimal annotationlib inspect_hex stat
_elementtree antigravity io statistics
_functools argparse ipaddress string
_hashlib array itertools stringprep
_heapq ast json struct
_hmac asyncio keyword subprocess
_imp atexit linecache symtable
_interpchannels base64 locale sys
_interpqueues bdb logging sysconfig
_interpreters binascii lzma tabnanny
_io bisect mailbox tarfile
_ios_support builtins main tempfile
_json bz2 marshal test
_locale cProfile math textwrap
_lsprof calendar math_demo this
_lzma certifi mimetypes threading
_markupbase charset_normalizer mmap time
_math_integer cmath modulefinder timeit
_md5 cmd msvcrt tkinter
_multibytecodec code multiprocessing token
_multiprocessing codecs netrc tokenize
_opcode codeop nt tomllib
_opcode_metadata collections ntpath trace
_operator colorsys nturl2path traceback
_osx_support compileall numbers tracemalloc
_overlapped compression opcode tty
_pickle concurrent operator turtle
_py_abc configparser optparse turtledemo
_py_warnings contextlib os types
_pydatetime contextvars pathlib typing
_pydecimal copy pdb unicodedata
_pyio copyreg pdf_decompress unittest
_pylong csv pdf_hex urllib
_pyrepl ctypes pdf_info urllib3
_queue curses pdf_info2 uuid
_random dataclasses pdf_metadata venv
_remote_debugging datetime pdf_pagecount warnings
_sha1 dbm pickle wave
_sha2 decimal pickletools weakref
_sha3 difflib pip webbrowser
_signal dis pkgutil winreg
_sitebuiltins doctest platform winsound
_socket email plistlib wsgiref
_sqlite3 encodings poplib xml
_sre ensurepip posixpath xmlrpc
_ssl enum pprint xxsubtype
_stat errno profile zipapp
_statistics extract_actualtext profiling zipfile
_string extract_actualtext2 pstats zipimport
_strptime extract_ascii pty zlib
_struct extract_chinese py_compile zoneinfo

Enter any module name to get more help. Or, type "modules spam" to search
for modules whose name or summary contain the string "spam".

不过,这个命令有一个需要注意的地方:它可能会扫描大量模块,执行时间较长;某些第三方模块在导入或扫描时还可能产生额外输出,甚至触发异常。因此,不建议每次查找功能时都依赖它。

更实用的做法是先根据需求缩小范围,再使用 help() 查看具体模块。

例如:

  • 处理文件路径,优先了解 pathlib。
  • 处理 JSON,优先了解 json。
  • 执行外部命令,优先了解 subprocess。
  • 获取 Python 解释器运行信息,优先了解 sys。

如果你已经知道模块名称,直接使用 help(模块名) 通常更高效。

查阅 Python 官方文档

当 help() 提供的信息不够直观,或者需要查看完整的示例、参数说明和注意事项时,Python 官方文档就是非常重要的参考资料。

官方文档地址:

Python 标准库文档(中文)

打开页面后,可以看到标准库按照不同功能进行了组织。你可以先从模块索引中找到目标模块,再查看其中的函数、类和使用说明。

例如,想了解 pathlib,可以进入对应文档:

Python pathlib 模块文档

假设我们需要获取某个日志文件的大小,可以在文档中查找 Path.stat() 等相关接口,然后编写代码:

1
2
3
4
5
6
7
8
9
from pathlib import Path

log_file = Path("/var/log/dnf.log")

if log_file.exists() and log_file.is_file():
size = log_file.stat().st_size
print(f"日志文件大小:{size / 1024:.2f} KiB")
else:
print("日志文件不存在,或者指定路径不是普通文件")

这里使用了 Path 对象的 exists()、is_file() 和 stat() 方法:

  • exists():检查路径是否存在。
  • is_file():判断路径是否指向普通文件。
  • stat():获取文件系统对象的属性,其中 st_size 表示文件大小,单位为字节。

需要注意,检查路径和读取属性之间仍可能发生文件被删除或权限发生变化等情况。在实际生产脚本中,如果文件状态可能随时变化,还应考虑使用异常处理。

再比如,你想编写一个脚本执行 df -h,并获取命令输出,可以查阅 subprocess 模块的文档:

Python subprocess 模块文档

通过文档可以进一步学习 subprocess.run() 的参数,以及如何获取返回码、标准输出和标准错误。

这种学习方式比单纯记住函数名称更有价值,因为官方文档不仅告诉你怎么使用,还会解释参数含义、返回结果以及使用限制。

注意区分标准库、第三方库和内置函数

查找模块时,还需要区分三个容易混淆的概念。

内置函数:Python 解释器提供的常用函数,通常不需要导入模块就能直接使用,例如 print()、len()、type() 和 dir()。

标准库模块:Python 安装后通常就能使用的模块,例如 os、sys、json、shutil 和 pathlib。使用其中的功能时,通常需要先通过 import 导入。

第三方库:由 Python 社区或其他组织提供,需要根据项目环境单独安装的库,例如 requests、numpy 和 pandas。

下面通过一个简单示例来区分它们:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 内置函数:不需要导入模块
print(len("Python"))

# 标准库模块:使用前导入
import json

data = {"name": "Linux", "status": "running"}
print(json.dumps(data))

# 第三方库:需要先安装 requests
# 安装命令:python3 -m pip install requests
#
# import requests
# response = requests.get("https://example.com", timeout=10)
# print(response.status_code)

其中,print() 和 len() 是内置函数;json 属于标准库;requests 则是第三方库。

实际工作中,如果标准库已经能够满足需求,通常可以优先考虑使用标准库,减少额外依赖。不过,如果第三方库能够显著简化复杂任务,也不必为了避免依赖而重复造轮子。

还要注意,某些 Python 发行版会裁剪组件,部分系统模块可能依赖操作系统或编译环境。因此,具体模块是否可用,仍应以当前 Python 环境和对应版本的官方文档为准。

养成先查文档、再写代码的习惯

学习 Python 时,不必把所有标准库模块和函数都背下来。更重要的是掌握查找和验证的方法。

当你遇到一个实际问题时,可以按照下面的步骤操作:

  • 明确需求:例如检查磁盘空间、读取配置文件或调用系统命令。
  • 查找模块:根据功能寻找可能适用的标准库模块。
  • 探索接口:使用 dir() 查看名称,使用 help() 查看具体说明。
  • 阅读文档:确认参数、返回值、异常和版本要求。
  • 编写并验证代码:先在测试环境中运行,再考虑应用到实际任务。

例如,面对一个陌生的标准库模块,不妨先尝试下面这几条命令:

1
2
3
4
5
6
7
8
9
10
import json

# 查看模块中有哪些名称
print(dir(json))

# 查看模块的整体帮助
help(json)

# 查看具体函数的帮助
help(json.loads)

通过这样的练习,你会逐渐从“记不住函数怎么办”,转变为“知道如何找到需要的函数”。

这也是学习编程非常重要的一项能力:不只是知道如何写代码,还要知道如何利用文档和工具解决自己尚未掌握的问题。

写在最后

Python 标准库提供了大量现成的功能,能够帮助我们处理文件、目录、系统命令、数据格式、日期时间以及网络通信等常见任务。

对于初学者来说,不必急着把所有模块都学完。先从 os、sys、pathlib、shutil、json 和 subprocess 等常用模块入手,遇到实际需求时再逐步扩展即可。

下一篇,我们将正式学习 Python 的 sys 模块,了解如何获取 Python 解释器的运行信息、读取命令行参数,以及控制程序的执行过程。