Python 开发技巧与工具集合
1. Python 编程习惯
1.1 代码可读性
使用
_
分隔大数字,提高可读性:python# 推荐 large_number = 10_000_000 # 不推荐 large_number = 10000000
使用
time.perf_counter()
来计时,而不是time.time()
:pythonimport time start = time.perf_counter() # 执行代码 end = time.perf_counter() print(f"执行时间: {end - start:.4f}秒")
使用
logging
模块来打印日志,而不是print()
:pythonimport logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) logger.info("这是一条信息") logger.warning("这是一条警告")
1.2 文件操作
使用 'x'
模式代替 'w'
进行写入,只有文件不存在时写入,如果存在则报错,防止覆盖:
try:
with open('file.txt', 'x') as f:
f.write("内容")
except FileExistsError:
print("文件已存在,防止覆盖")
1.3 异步编程
使用 asyncio.create_subprocess_exec
和 asyncio.create_subprocess_shell
创建异步子进程:
import asyncio
async def run_command():
# 使用 create_subprocess_exec
proc = await asyncio.create_subprocess_exec(
'python', '--version',
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await proc.communicate()
# 使用 create_subprocess_shell
proc = await asyncio.create_subprocess_shell(
'ls -la',
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await proc.communicate()
使用 asyncio.to_thread()
在异步代码中运行阻塞函数:
import asyncio
def blocking_function(arg):
# 执行阻塞操作
return result
async def main():
# 在新线程中运行阻塞函数
result = await asyncio.to_thread(blocking_function, arg_value)
参考资料:How to Use Asyncio to_thread() - Super Fast Python
2. Python 实用工具库
2.1 日志工具
Loguru:简化 Python 日志记录的现代化日志库。
from loguru import logger
logger.info("这是一条信息")
logger.error("这是一条错误")
2.2 网络请求
HTTPX:现代化的 HTTP 客户端,支持同步和异步请求。
可选依赖:
h2
- HTTP/2 支持(httpx[http2]
)socksio
- SOCKS 代理支持(httpx[socks]
)rich
- 富终端支持(httpx[cli]
)click
- 命令行客户端支持(httpx[cli]
)brotli
或brotlicffi
- Brotli 压缩支持(httpx[brotli]
)
pip install httpx[http2,socks,cli,brotli]
2.3 Web 爬虫
ruia:异步 Web 数据采集的 Python 框架。
trafilatura:用于提取和解析网络页面内容的 Python 工具。
参考:trafilatura 用于提取和解析网络页面内容的Python工具
2.4 视频处理
vidgear:用于高效视频处理的 Python 库。
2.5 热键监听
PyHotKey:用于监听和处理全局热键的 Python 库。
2.6 Redis 分布式锁
使用 Redis 实现分布式锁:
2.7 实用模块集合
Python 实用模块教程:https://xugaoxiang.com/category/python/modules/
3. Python 性能优化
3.1 Pandas 性能优化
提速百倍的 Pandas 性能优化方法:
参考:提速百倍的 Pandas 性能优化方法,让你的 Pandas 飞起来!
3.2 使用 Cython 优化
将 Python 项目转化为 .so
文件:
参考:尝试利用 Cython 将 Python 项目转化为单个 .so
3.3 使用 Nuitka 打包
Nuitka 是一个 Python 到 C++ 的编译器,可以将 Python 代码编译为可执行文件。
参考资料:
4. Python Web 开发
4.1 Sanic 高并发服务
Sanic 是一个类似 Flask 的 Python 3.7+ Web 框架,专为快速 HTTP 响应而设计。
4.2 SQLite WAL 模式
在 Python 中使用 SQLite 的 WAL(Write-Ahead Logging)模式:
import sqlite3
conn = sqlite3.connect('database.db')
conn.execute('PRAGMA journal_mode=WAL')
5. Python 项目构建
5.1 虚拟环境方案
各种不同的 Python 虚拟环境方案对比:
- venv(Python 内置)
- virtualenv
- conda
- poetry
- pipenv
5.2 构建工具
hatchling:现代化的 Python 项目构建后端。
5.3 插件系统
构建 Python 插件系统的最佳实践。
6. Python 高级应用
6.1 Everything SDK
调用 Everything SDK,实现全局文件搜索功能。
6.2 类型字典
使用 TypedDict
构造类型字典:
from typing import TypedDict
class Person(TypedDict):
name: str
age: int
email: str
person: Person = {
"name": "张三",
"age": 30,
"email": "zhangsan@example.com"
}
6.3 代数系统
如何构建像 SymPy 一样的代数系统。
6.4 Python + WebAssembly
将 Python 代码编译为 WebAssembly,在浏览器中运行。
7. Python 任务调度
7.1 周期性任务调度框架
构建周期性任务调度框架的设计模式。
7.2 视频处理框架
构建通用的视频处理框架。
8. 域名 SSL 证书检查
获取域名 SSL 证书信息和到期时间:
9. 模块搜索路径
Python 模块搜索路径的工作原理:
参考:模块搜索路径
10. PySide6 开发
10.1 Tree/Table 组件扩展
在 PySide6 中添加 Tree/Table 扩展最后一行/列的功能。