打开文件
with open('em.txt', 'wb') as f: f.write('ememem')
线程lock
lock = threading.Lock()# with里面获取lock, 退出with后释放lockwith lock: # Critical section of code ...
数据库游标
db_connection = DatabaseConnection()with db_connection as cursor: # with里面获取cursor, 退出with后释放cursor cursor.execute('insert into ...') cursor.execute('delete from ...') # ... more operations ...
同时获取lock和数据库游标
lock = threading.Lock()cur = db.cursor()with cur as cu, lock as locked: ...
请求后关闭
import urllib, sysfrom contextlib import closingwith closing(urllib.urlopen('http://www.yahoo.com')) as f: for line in f: sys.stdout.write(line)