Python 中的上下文管理器关闭资源
除了文件操作,上下文管理器还有哪些典型应用场景?请给出锁、数据库连接、临时改变属性的例子。
回答
我还是少年
1. 线程锁:
import threading
lock = threading.Lock()
with lock:
# 自动 acquire/release
pass
2. 数据库连接:
from contextlib import closing
import sqlite3
with closing(sqlite3.connect('db.sqlite')) as conn:
with conn:
conn.execute('INSERT INTO users VALUES (?)', ('Alice',))
3. 临时改变属性:
from contextlib import contextmanager
@contextmanager
def temp_attr(obj, name, value):
original = getattr(obj, name)
setattr(obj, name, value)
try:
yield
finally:
setattr(obj, name, original)
with temp_attr(sys, 'path', ['/tmp']):
import mymodule
4. 重定向输出:contextlib.redirect_stdout()
5. 忽略异常:contextlib.suppress(FileNotFoundError)