Appearance
Python Cheatsheet
- 内嵌 Jupyter Notebook
subprocess
py
result = subprocess.run(command, shell=True, capture_output=True, text=True)
result.returncode
result.stderr
result.returncode
p = subprocess.Popen(cmd, shell=exe_in_shell, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
p.wait() # 等待子进程结束
p.poll() # 检查子进程是否已结束,不阻塞等待
subprocess.PIPE = -1
subprocess.STDOUT = -2
subprocess.DEVNULL = -3threading
py
import threading
import queue
from functools import partial
t = threading.Thread(target=thread_fn, args=(1,), daemon=True)
t.start()
t.join() # 等待线程结束
# 线程同步
e = threading.Event()
e.wait()
e.set()
e.clear()
# 线程互斥 共享资源
lock = threading.Lock()
lock.acquire()
lock.release()
# 线程安全的队列
q = queue.Queue()
q.put(1)
item = q.get()
# 使用 functools.partial 预先绑定一些参数
def worker(arg1, arg2, arg3):
print(f"arg1: {arg1}, arg2: {arg2}, arg3: {arg3}")
worker_partial = partial(worker, 1, 2)
thread = threading.Thread(target=worker_partial, args=(3,))queue
py
import queue
q = queue.Queue(maxsize=1)
q.put(1)
item = q.get()functools
py
from functools import partial, wraps
partial:固定部分参数,创建新的函数。
wraps:用于装饰器,保留原函数的元数据。dataclasses
py
from dataclasses import dataclass, asdict, astuple
@dataclass
class Point:
x: int
y: int
# __init__
# __repr__: 自动生成对象的字符串表示方法
# __eq__
p = Point(1, 2)
print(p) # 输出: Point(x=1, y=2)ctypes
py
import ctypes
ctypes.CDLL(typing
py
from typing import Any, Optional, List, Tuple, Callable, Dict
from typing import Any, Dict, IO, Iterator, List, Optional, Tuple, Unionconcurrent.futures
py
from concurrent.futures import ThreadPoolExecutor, as_completed, Futurenumpy
numpy 处理视频、音频、图片数据
py
import numpy as np
# 二进制数据(例如 4 个 float32 数字)
data = b'\x00\x00\x00\x00\x00\x00\x80?\x00\x00\x00@\x00\x00\x80@'
# 转换为 float32 数组
arr = np.frombuffer(data, dtype=np.float32)
print(arr) # 输出: [0. 1. 2. 4.]cv2
py
import cv2requests
py
import requestsjson
py
import json
data = {
"name": "Alice",
"age": 30,
"is_student": False,
"courses": ["Math", "Physics"]
}
# 转换为 JSON 字符串
json_str = json.dumps(data, indent=4) # indent 用于美化输出
print(json_str)traceback
py
import trackback泛型
TODO
虚拟环境
见命令行大全
time
py
import time
time.sleep(3)datetime
py
import datetime
# 获取当前时间
now = datetime.now()
now = datetime.now().time()
# 日期2字符串
formatted = dt.strftime("%Y-%m-%d %H:%M:%S")
# 字符串2日期
dt = datetime.strptime("2024-08-19 22:05:00", "%Y-%m-%d %H:%M:%S")pyaudio
py
import pyaudiopyav
py
import av
# ffmpegenum
py
from enum import Enumwav / librosa 音频库
import wave
import librosaimport asyncio # 协程包
import zmq
import torch import torch.cuda
import shutil
signal
py
import signal
signal.signal(signal.SIGINT, keyboard_interrupt_signal_handler)fastapi
py
from fastapi import Request, BackgroundTasks
import uvicornface_alignment
py
from face_alignment 人脸检测包装饰器
py
@staticmethod
@classmethod
from dataclasses import dataclasstqdm
py
import tqdm 进度条setuptools
TODO
内置函数
isinstance hasattr
web 项目示例
Python 实战 · 从 0 到 1 搭建直播视频平台
TensorFlow 或 PyTorch 等深度学习框架和 opencv、人脸识别有什么关系啊
3. 结合使用
前处理和后处理: 在实际项目中,OpenCV 常常用于图像的前处理和后处理,比如从视频流中检测出人脸区域,并将这些区域输入到 TensorFlow 或 PyTorch 训练好的模型中进行识别。识别结果(如身份标签、情感状态)可以通过 OpenCV 的工具进行可视化展示。
模型部署: 在一些实际应用中,训练好的深度学习模型可以通过 OpenCV 的 DNN 模块部署,以实现实时性较高的人脸识别任务。
总结
OpenCV 提供了基本的人脸检测和图像处理功能,而 TensorFlow 和 PyTorch 则为人脸识别任务提供了训练复杂神经网络模型的能力。在实际项目中,通常将 OpenCV 用于图像处理,而将 TensorFlow 或 PyTorch 用于构建和训练深度学习模型,然后将它们结合在一起实现更高效的人脸识别系统。Jupyter Notebook
Jupyter Notebook 为什么是现代 Python 的必学技术?-Python 核心技术与实战-极客时间
pyinstaller
py
pyinstaller其它
- import pika.spec
- from opentelemetry import trace
- import io
- import tenacity
- import tempfile
- import uuid
私有函数
py
__init__
__super__staticmethod
待整理
traceback.format_exc()- threading 操作包括:daemon、start 和 join
- 判断列表为空
if self.log_queue: - 获取循环中元素的索引
enumerate() import concurrent.futureswith concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:executor.submit(fn, args...)
- threading.Event() 是 Python 的 threading 模块中一个用于线程间同步的对象。
- set
- clear
- wait
- is_set
- requests 的 resp.raise_for_status() 方法
cv2.VideoCapture(打开视频流cv2.CAP_PROP_FRAME_COUNT从视频流中获取总帧数ret, f = video_stream.read()读取视频帧 ret 为是否成功,f 为当前帧(一个表示图像 NumPy 数组)- cv2.CAP_PROP_FPS 获取视频的帧率(FPS,
- Blend.frame_h, Blend.frame_w = f.shape[0:2] 获取图像的高度和宽度。
- f.shape 是 NumPy 数组的一个属性,用于获取数组的维度。对于图像(视频帧)来说,通常有三个维度:高度、宽度和通道数(例如 RGB 有 3 个通道)。
- f.shape[0:2] 获取图像的高度和宽度。
dll_path = os.path.join(cls.root_path, '_internal', 'internalt.dll') if not dll_path else dll_path- Union 是 Python 的 typing 模块中的一个泛型类,用于指定变量可以接受的多种类型。
疑问:
- logger 和 msg_logger 的区别
- control 控制与前端的消息交互
- main_loop 循环播放素材并调用 blend 推理嘴形:通过音频驱动嘴形
- 音频如何跟画面同步的
资源散积地
The Hitchhiker’s Guide to Python!
编码规约
- Python 官方编码规范
- Google Code Style Guide
- The Black code style
- Pythonic 风格指南
- Exercises in Programming Style 随书代码
2
- PEP 8 – Style Guide for Python Code
- How to Write Beautiful Python Code With PEP 8
- PEP 20 – The Zen of Python
- PEP 20 (The Zen of Python) by example
- The Black code style
- Google Python Style Guide
- 代码风格 - The Hitchhiker's Guide to Python
- Linux kernel coding style
库
PyYAML
安装:pip install pyyaml
py
import yaml
# 从文件加载 YAML 数据
with open('data.yaml', 'r') as file:
data = yaml.safe_load(file)
# 获取 MySQL 主机配置
mysql_host = data['mysql']['host']pymysql
安装:pip install pymysql
py
import pymysql
connection = pymysql.connect(host='localhost', user='username', password='password', database='dbname')
# 查询
cursor = connection.cursor()
cursor.execute("SELECT * FROM table")
results = cursor.fetchall()
cursor.close()
# 插入
cursor = connection.cursor()
cursor.execute("INSERT INTO table (column1, column2) VALUES (%s, %s)", (value1, value2))
connection.commit()
cursor.close()