Python3标准库核心模块速查与实战

七月
七月
发布时间:2026-10-11| 3人浏览过
原创

Python3 提供了丰富的标准库,覆盖了从文件管理、系统交互到网络通信和测试的广泛需求。本文精选了开发中最常用的核心模块,通过具体代码示例展示其关键用法,包括文件操作、正则表达式、时间处理及性能测试等,帮助开发者高效利用内置资源。

文件与目录管理

在 Python 中,处理文件系统是常见任务。推荐使用 import os 而非 from os import *,以避免命名冲突,例如防止 os.open() 覆盖内置的 open() 函数。

os 模块:基础文件操作

os 模块提供了与操作系统交互的接口,包括获取和修改当前工作目录、执行系统命令等。

import os
# 获取当前工作目录
print(os.getcwd())  # 输出类似 'C:\Python34'
# 切换工作目录
os.chdir('/server/accesslogs')
# 执行系统命令
os.system('mkdir today')

若需查看模块中所有可用函数,可使用 dir(os);获取详细文档则使用 help(os)。

shutil 与 glob:高级文件处理

shutil 模块提供了更高级的文件和目录管理接口,如文件复制和移动。而 glob 模块则用于通过通配符搜索目录中的文件。

import shutil
# 复制文件
shutil.copyfile('data.db', 'archive.db')
# 移动文件
shutil.move('/build/executables', 'installdir')

import glob
# 获取当前目录下所有 .py 文件
print(glob.glob('*.py'))  # 输出: ['primes.py', 'random.py', 'quote.py']

系统交互与命令行参数

sys 模块提供了访问由 Python 解释器使用或维护的变量,以及与解释器紧密交互的函数。

命令行参数与标准流

脚本的命令行参数以列表形式存储在 sys.argv 中。此外,sys 模块包含 stdin、stdout 和 stderr 属性。当标准输出被重定向时,可以使用 sys.stderr 来显示警告或错误信息,确保用户能接收到关键提示。

import sys
# 打印命令行参数
print(sys.argv)  # 输出: ['demo.py', 'one', 'two', 'three']
# 写入标准错误流
sys.stderr.write('Warning, log file not found starting a new one\n')

脚本正常终止通常使用 sys.exit()。

文本处理与数学运算

正则表达式:re 模块

虽然简单的字符串替换可以使用内置方法(如 'tea for too'.replace('too', 'two')),但复杂模式匹配应使用 re 模块。

import re
# 查找所有以 f 开头、后跟小写字母的单词
print(re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest'))
# 输出: ['foot', 'fell', 'fastest']

# 替换重复单词
print(re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat'))
# 输出: 'cat in the hat'

数学与随机数

math 模块提供了对底层 C 函数库的访问,支持浮点运算。而 random 模块则用于生成各种类型的随机数。

import math
# 计算余弦值
print(math.cos(math.pi / 4))  # 输出: 0.70710678118654757
# 计算对数
print(math.log(1024, 2))      # 输出: 10.0

import random
# 从列表中随机选择一个元素
print(random.choice(['apple', 'pear', 'banana']))
# 无放回抽样
print(random.sample(range(100), 10))
# 生成随机浮点数
print(random.random())
# 生成指定范围内的随机整数
print(random.randrange(6))

网络通信与时间处理

URL 处理与邮件发送

urllib.request 模块用于处理从 URL 接收的数据。以下示例展示了如何从指定 URL 获取数据并解码为文本。

from urllib.request import urlopen
# 获取网页内容并解码
for line in urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):
    line = line.decode('utf-8')
    if 'EST' in line or 'EDT' in line:
        print(line)

smtplib 模块用于发送电子邮件。注意,使用此模块通常需要本地运行邮件服务器。

import smtplib
server = smtplib.SMTP('localhost')
server.sendmail('soothsayer@example.org', 'jcaesar@example.org',
"""To: jcaesar@example.org
From: soothsayer@example.org

Beware the Ides of March.
""")
server.quit()

日期与时间:datetime 模块

datetime 模块支持日期和时间的算法及格式化输出,并支持时区处理。

from datetime import date
# 获取当前日期
now = date.today()
print(now)  # 输出: datetime.date(2003, 12, 2)
# 格式化日期
print(now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B."))
# 计算年龄
birthday = date(1964, 7, 31)
age = now - birthday
print(age.days)  # 输出: 14368

数据压缩与性能测试

数据压缩

zlib、gzip、bz2、zipfile 和 tarfile 模块支持数据的打包和压缩。以下示例展示了 zlib 的基本用法。

import zlib
s = b'witch which has which witches wrist watch'
t = zlib.compress(s)
print(zlib.decompress(t))  # 输出: b'witch which has which witches wrist watch'
print(zlib.crc32(s))       # 输出: 226805979

性能测试

timeit 模块用于度量解决同一问题的不同方法的性能差异,而 profile 和 pstats 模块则针对更大的代码块进行时间度量。

from timeit import Timer
# 比较两种交换变量值的方法
print(Timer('t=a; a=b; b=t', 'a=1; b=2').timeit())
print(Timer('a,b = b,a', 'a=1; b=2').timeit())

自动化测试

doctest 模块

doctest 模块扫描模块并执行内嵌文档字符串中的测试,通过用户提供的例子强化文档。

def average(values):
  """Computes the arithmetic mean of a list of numbers.

  >>> print(average([20, 30, 70]))
  40.0
  """
  return sum(values) / len(values)

import doctest
doctest.testmod()  # 自动验证嵌入测试

unittest 模块

unittest 模块可在独立文件中提供更全面的测试集。

import unittest

class TestStatisticalFunctions(unittest.TestCase):

  def test_average(self):
    self.assertEqual(average([20, 30, 70]), 40.0)
    self.assertEqual(round(average([1, 5, 7]), 1), 4.3)
    self.assertRaises(ZeroDivisionError, average, [])
    self.assertRaises(TypeError, average, 20, 30, 70)

unittest.main() # 从命令行调用将运行所有测试

以上就是Python3标准库核心模块的详细内容,更多关于Python3标准库、os模块、sys模块、re模块、datetime模块的资料请关注本站其它相关文章!

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。