Python

语言规范 python之禅 pythonic 命名 语法 数据 变量定义 作用域 数据结构 运算 流程控制 条件 循环 函数 定义 调用 常用函数 map filter range enumerate 导包 import util as u from util.file_util import read_lines from util.log_util import * 异常处理 AOP python_aop 多线程 多线程&多进程 由于GIL(全局解释器锁),Python多线程无法真正并行(仅并发)。 多进程可绕过GIL,实现真正的并行(利用多核CPU)。 多进程: import os from multiprocessing import Process def process_task(name): print(f"子进程 {name} PID: {os.getpid()},父进程 PID: {os.getppid()}") if __name__ == '__main__': p = Process(target=process_task, args=('child',)) p.start() p.join() print(f"主进程 PID: {os.getpid()}") 进程池 from mulitprocessing import Pool from multiprocessing import Process, Lock import time def process_task(lock, filepath): with lock: # 进程间文件访问需要锁 with open(filepath, 'a') as f: f.write(f"Process {os.getpid()} wrote at {time.time()}\n") if __name__ == '__main__': lock = Lock() # 跨进程锁 filepath = 'shared.log' processes = [Process(target=process_task, args=(lock, filepath)) for _ in range(3)] for p in processes: p.start() for p in processes: p.join() 多线程 import threading def thread_task(name): print(f"线程 {name} 正在执行") threads = [] for i in range(3): t = threading.Thread(target=thread_task, args=(f'Thread-{i}',)) threads.append(t) t.start() for t in threads: t.join() 线程池 from concurrent.futures import ThreadPoolExecutor import requests def fetch_url(url): response = requests.get(url) return f"{url}: {len(response.content)} bytes" urls = ["https://www.python.org", "https://www.google.com", "https://www.github.com"] # 使用线程池(适合I/O阻塞操作) with ThreadPoolExecutor(max_workers=3) as executor: results = list(executor.map(fetch_url, urls)) print(results) 锁仅针对于多线程 import threading counter = 0 lock = threading.Lock() def increment(): global counter for _ in range(100000): with lock: # 自动获取和释放锁 counter += 1 threads = [threading.Thread(target=increment) for _ in range(5)] for t in threads: t.start() for t in threads: t.join() print(f"最终计数器值: {counter}") # 应该是500000 文件操作 with open('.bashrc', 'r', encoding='utf-8') as f: f.readlines() f.wirtelines() 网络编程 数据库相关 redis import redis # 连接 pool = redis.ConnectionPool(host='localhost', port=6379, db=0) r = redis.Redis(connection_pool=pool) # 操作 r.set('visits', 0) r.incr('visits') print(f"Total visits: {r.get('visits').decode()}") mysql SQLAlchemy ...

2026-04-03 · 2 分钟 · ziwindlu · 源笔记:02-Knowledge/编程/Python.md

python_aop

前置知识 切面(Aspect): 封装横切关注点的模块 连接点(Join Point): 程序执行过程中的特定点(如方法调用) 通知(Advice): 在连接点执行的动作(如方法执行前后) 切入点(Pointcut): 定义哪些连接点会被通知影响 一般写法 装饰器 def log_aspect(func): def wrapper(*args, **kwargs): print(f"开始执行: {func.__name__}") result = func(*args, **kwargs) print(f"结束执行: {func.__name__}") return result return wrapper @log_aspect def business_method(): print("执行业务逻辑...") business_method() 使用类装饰器 class TransactionAspect: def __init__(self, func): self.func = func def __call__(self, *args, **kwargs): print("开启事务") try: result = self.func(*args, **kwargs) print("提交事务") return result except Exception as e: print("回滚事务") raise e @TransactionAspect def process_order(): print("处理订单业务...") process_order() 使用上下文管理器 class PerformanceAspect: def __enter__(self): self.start = time.time() def __exit__(self, exc_type, exc_val, exc_tb): print(f"耗时: {time.time() - self.start:.4f}秒") def business_logic(): with PerformanceAspect(): print("执行业务逻辑...") time.sleep(1) business_logic()

2026-04-03 · 1 分钟 · ziwindlu · 源笔记:02-Knowledge/编程/python_aop.md

python使用requirements管理依赖

引子 写了个python工具,其中用了一些依赖,不想要手动整理依赖放到requests.txt中。俺想到肯定有懒人用法,于是有了今天的文章。使用pipreqs来管理 安装 pip install pipreqs 用法 一步搞定 pipreqs /path/to/project 这样就生成了一个requirements.txt啦 通过requirements.txt安装依赖 pip install -r requirements.txt 参考 id:: 66264e12-b7c5-48bc-b37b-d0fbd31330f0) python生成requirements.txt的两种方法 数据驱动 博客园

2024-04-24 · 1 分钟 · ziwindlu · 源笔记:02-Knowledge/编程/python使用requirements管理依赖.md