常用第三方模块
Python拥有丰富的第三方库生态系统,本章介绍最常用的一些第三方模块,帮助你快速构建应用程序。
pip包管理
pip是Python官方的包管理工具,可以帮助我们安装、升级、卸载Python第三方库。
命令
# 安装包
pip install requests
# 安装指定版本
pip install requests==2.28.0
# 安装requirements.txt中的所有包
pip install -r requirements.txt
# 升级包到最新版本
pip install --upgrade requests
# 卸载包
pip uninstall requests
# 查看已安装的包
pip list
# 导出已安装的包到requirements.txt
pip freeze > requirements.txt
💡 提示:如果遇到Permission denied错误,在Linux/Mac上使用sudo,在Windows上以管理员身份运行命令行。
virtualenv虚拟环境
virtualenv可以创建独立的Python环境,避免不同项目之间的依赖冲突。
┌─────────────────────────────────────────────────────────┐ │ 系统Python环境 │ │ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ │ │项目A依赖 │ │项目B依赖 │ │项目C依赖 │ │ │ │Django 4 │ │Django 3 │ │Django 2 │ │ │ └─────────┘ └─────────┘ └─────────┘ │ │ ❌ 版本冲突! │ └─────────────────────────────────────────────────────────┘ ┌─────────────────────────────────────────────────────────┐ │ 使用virtualenv后:每个项目独立环境 │ ├─────────────────────────────────────────────────────────┤ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ │ 环境A │ │ 环境B │ │ 环境C │ │ │ │ ┌─────────┐ │ │ ┌─────────┐ │ │ ┌─────────┐ │ │ │ │ │Django 4 │ │ │ │Django 3 │ │ │ │Django 2 │ │ │ │ │ └─────────┘ │ │ └─────────┘ │ │ └─────────┘ │ │ │ └─────────────┘ └─────────────┘ └─────────────┘ │ │ ✅ ✅ ✅ │ └─────────────────────────────────────────────────────────┘
命令
# 安装virtualenv
pip install virtualenv
# 创建虚拟环境
virtualenv myenv
# 激活虚拟环境 (Linux/Mac)
source myenv/bin/activate
# 激活虚拟环境 (Windows)
myenv\Scripts\activate
# 在虚拟环境中安装包
pip install django
# 退出虚拟环境
deactivate
requests网络请求
requests是目前最流行的HTTP库,用于发送各种HTTP请求、处理响应和错误。
Python
# 安装: pip install requests
import requests
# ===== GET请求 =====
response = requests.get("https://api.github.com")
print(response.status_code) # 200
print(response.json()) # 解析JSON响应
# 带参数的GET请求
params = {"q": "python", "page": 1, "per_page": 10}
response = requests.get("https://api.github.com/search/repositories",
params=params)
print(response.url) # 自动编码为URL参数
# ===== POST请求 =====
# 表单数据
response = requests.post("https://httpbin.org/post",
data={"username": "admin", "password": "123456"})
# JSON数据 (推荐)
response = requests.post("https://httpbin.org/post",
json={"title": "Python教程", "content": "详细内容..."})
# ===== 请求头和Cookie =====
headers = {"User-Agent": "Mozilla/5.0", "Authorization": "Bearer xxx"}
cookies = {"session_id": "abc123"}
response = requests.get("https://api.example.com/user",
headers=headers, cookies=cookies)
# ===== 上传文件 =====
with open("report.xls", "rb") as f:
files = {"file": f}
response = requests.post("https://httpbin.org/post", files=files)
# ===== 超时设置 =====
response = requests.get("https://api.example.com", timeout=5)
# ===== 响应内容 =====
print(response.text) # 文本内容
print(response.content) # 二进制内容
print(response.json()) # JSON解析
print(response.headers) # 响应头
print(response.cookies) # Cookie
print(response.status_code) # 状态码
💡 最佳实践:始终为请求设置timeout参数,避免程序在网络异常时无限等待。
psutil系统监控
psutil = process and system utilities,跨平台的系统监控工具,可以获取CPU、内存、磁盘、网络等信息。
┌──────────────────────────────────────────────────────┐ │ 系统资源监控 │ ├──────────────────────────────────────────────────────┤ │ ┌────────────┐ ┌────────────┐ ┌────────────┐ │ │ │ CPU │ │ 内存 │ │ 磁盘 │ │ │ │ ┌──────┐ │ │ ┌──────┐ │ │ ┌──────┐ │ │ │ │ │核心: 8│ │ │ │总量: │ │ │ │总量: │ │ │ │ │ │使用:25%│ │ │ │16GB │ │ │ │500GB │ │ │ │ │ └──────┘ │ │ │使用: │ │ │ │使用: │ │ │ │ │ │ │ │45% │ │ │ │39% │ │ │ │ │ │ │ └──────┘ │ │ └──────┘ │ │ │ └────────────┘ └────────────┘ └────────────┘ │ │ │ │ ┌────────────┐ ┌────────────┐ │ │ │ 网络 │ │ 进程 │ │ │ │ ┌──────┐ │ │ ┌──────┐ │ │ │ │ │发送: │ │ │ │PID: │ │ │ │ │ │1.2GB │ │ │ │1234 │ │ │ │ │ │接收: │ │ │ │名称: │ │ │ │ │ │3.5GB │ │ │ │python│ │ │ │ │ └──────┘ │ │ └──────┘ │ │ │ └────────────┘ └────────────┘ │ └──────────────────────────────────────────────────────┘
Python
# 安装: pip install psutil
import psutil
# ===== CPU信息 =====
print(f"CPU数量: {psutil.cpu_count()}") # 逻辑CPU数量
print(f"物理CPU: {psutil.cpu_count(logical=False)}") # 物理核心数
print(f"CPU使用率: {psutil.cpu_percent(interval=1)}%") # 每秒刷新
print(f"CPU使用率(每个核心): {psutil.cpu_percent(interval=1, percpu=True)}")
# ===== 内存信息 =====
mem = psutil.virtual_memory()
print(f"内存总量: {mem.total / (1024**3):.2f} GB")
print(f"内存使用: {mem.used / (1024**3):.2f} GB")
print(f"内存使用率: {mem.percent}%")
print(f"可用内存: {mem.available / (1024**3):.2f} GB")
# ===== 磁盘信息 =====
print("磁盘分区:")
for partition in psutil.disk_partitions():
print(f" {partition.device} -> {partition.mountpoint} ({partition.fstype})")
disk = psutil.disk_usage("/")
print(f"磁盘总量: {disk.total / (1024**3):.2f} GB")
print(f"磁盘使用: {disk.used / (1024**3):.2f} GB")
print(f"磁盘使用率: {disk.percent}%")
# ===== 网络信息 =====
net = psutil.net_io_counters()
print(f"发送字节: {net.bytes_sent / (1024**2):.2f} MB")
print(f"接收字节: {net.bytes_recv / (1024**2):.2f} MB")
# ===== 进程管理 =====
print("当前进程信息:")
p = psutil.Process()
print(f" 进程名: {p.name()}")
print(f" PID: {p.pid}")
print(f" 内存使用: {p.memory_info().rss / (1024**2):.2f} MB")
print(f" CPU使用率: {p.cpu_percent():.1f}%")
print(f" 线程数: {p.num_threads()}")
# 遍历所有进程
for proc in psutil.process_iter(['pid', 'name'])[:5]:
print(f"PID: {proc.info['pid']}, Name: {proc.info['name']}")
Pillow图像处理
Pillow是Python Imaging Library (PIL)的fork版本,是最常用的图像处理库。
Python
# 安装: pip install Pillow
from PIL import Image, ImageFilter, ImageDraw, ImageFont
# ===== 基本操作 =====
img = Image.open("photo.jpg")
print(img.size, img.format, img.mode) # (width, height), 'JPEG', 'RGB'
# 调整大小
img_resized = img.resize((800, 600))
img_resized.save("photo_resized.jpg")
# 缩略图 (保持比例)
img.thumbnail((200, 200))
# 旋转和翻转
img_rotated = img.rotate(45) # 顺时针旋转45度
img_flipped = img.transpose(Image.FLIP_LEFT_RIGHT) # 左右翻转
# 裁剪 (left, top, right, bottom)
img_cropped = img.crop((100, 100, 400, 300))
# ===== 图像模式转换 =====
img_gray = img.convert("L") # 转为灰度图
img_rgba = img.convert("RGBA") # 转为RGBA模式
# ===== 滤镜效果 =====
img_blur = img.filter(ImageFilter.BLUR) # 模糊
img_sharp = img.filter(ImageFilter.SHARPEN) # 锐化
img_edge = img.filter(ImageFilter.FIND_EDGES) # 边缘检测
img_contour = img.filter(ImageFilter.CONTOUR) # 轮廓
# ===== 绘图和文字 =====
img = Image.open("photo.jpg")
draw = ImageDraw.Draw(img)
# 画矩形
draw.rectangle([50, 50, 150, 100], outline="red", width=2)
# 画圆形
draw.ellipse([200, 50, 300, 150], fill="blue", outline="black")
# 画文字
font = ImageFont.truetype("arial.ttf", 36)
draw.text((300, 100), "Hello!", fill="white", font=font)
# 画线条
draw.line([0, 0, 100, 100], fill="green", width=3)
img.save("photo_annotated.jpg")
# ===== 创建新图像 =====
# 创建纯色图像
new_img = Image.new("RGB", (400, 300), color="white")
# 创建渐变图像
for x in range(400):
for y in range(300):
r = int(x / 400 * 255)
g = int(y / 300 * 255)
b = 128
new_img.putpixel((x, y), (r, g, b))
# ===== 图像合成 =====
img1 = Image.open("image1.png")
img2 = Image.open("image2.png")
mask = Image.open("mask.png").convert("L")
img1.paste(img2, (50, 50), mask) # 使用mask控制透明度
chardet字符编码检测
chardet可以自动检测字符编码,解决编码识别问题。
Python
# 安装: pip install chardet
import chardet
# 检测字节串编码
data = "你好世界".encode("utf-8")
result = chardet.detect(data)
print(result)
# {'encoding': 'utf-8', 'confidence': 0.99, 'language': ''}
# 检测文件编码
with open("document.txt", "rb") as f:
raw_data = f.read()
encoding = chardet.detect(raw_data)
print(f"检测到编码: {encoding['encoding']}")
print(f"置信度: {encoding['confidence'] * 100}%")
content = raw_data.decode(encoding['encoding'])
# 自动读取任意编码文件
def read_file_auto_encoding(filepath):
with open(filepath, "rb") as f:
raw = f.read()
detected = chardet.detect(raw)
return raw.decode(detected['encoding'])
content = read_file_auto_encoding("unknown_encoding.txt")
print(content)
章节总结
常用第三方模块速查表
| 模块 | 用途 | 安装命令 |
|---|---|---|
| requests | HTTP网络请求 | pip install requests |
| psutil | 系统监控 | pip install psutil |
| Pillow | 图像处理 | pip install Pillow |
| chardet | 字符编码检测 | pip install chardet |
| virtualenv | 虚拟环境管理 | pip install virtualenv |
关键知识点:
- pip是Python官方包管理工具,用于安装、升级、卸载第三方库
- virtualenv创建独立环境,避免项目间依赖冲突
- requests是目前最流行的HTTP库,比urllib更易用
- psutil跨平台获取系统CPU、内存、磁盘、网络、进程信息
- Pillow支持图像打开、保存、缩放、旋转、滤镜、绘图等操作
- chardet自动检测未知文件的字符编码
课后测验
问题1:以下哪个命令可以查看已安装的所有Python包?
问题2:使用requests发送POST请求并传递JSON数据,应该使用哪个参数?
问题3:psutil获取当前进程对象的正确方式是?
课后练习
练习1:批量图片处理
编写一个程序,将指定文件夹中的所有图片文件缩放到50%,并保存到新文件夹中。
提示
- 使用os.listdir()遍历文件夹
- 检查文件扩展名(如.jpg, .png)
- 使用Pillow打开、处理、保存图片
练习2:系统监控脚本
编写一个监控脚本,每5秒输出一次CPU使用率、内存使用率、磁盘使用率,并在超过阈值时发出警告。
提示
- 使用time模块实现定时
- psutil.cpu_percent()获取CPU使用率
- psutil.virtual_memory()获取内存信息
- psutil.disk_usage()获取磁盘信息
🐍 Python 在线代码编辑器
📝 运行结果