本文共 780 字,大约阅读时间需要 2 分钟。
在Python中,with语句是一种有效的资源管理机制,用于确保资源在使用后能够被正确释放,无论是否发生异常。常见的资源类型包括文件、数据库连接、线程锁等。通过使用with语句,开发者可以简洁地管理资源的获取和释放过程,避免手动操作带来的潜在风险。
with open('example.txt', 'r') as f: for line in f: print(line.strip()) # 文件在with代码块结束后自动关闭 import sqlite3 with sqlite3.connect('example.db') as conn: cursor = conn.cursor() cursor.execute("SELECT * FROM users") rows = cursor.fetchall() for row in rows: print(row) # 连接在with代码块结束后自动关闭 import threading lock = threading.Lock() with lock: print("Thread is running") # 创建多个线程并启动 threads = [] for _ in range(5): thread = threading.Thread(target=thread_function) threads.append(thread) thread.start() # 等待所有线程执行完成 for thread in threads: thread.join() 转载地址:http://eyofk.baihongyu.com/