Python with 用法
with open('em.txt', 'w') as f:
f.write('ememem')
等价于
tmp = open('em.txt', 'w')
f = tmp.__enter__()
#tmp == f True
f.write('ememem')
f.__exit__()
print(f)
# <_io.TextIOWrapper name='em.txt' mode='w' encoding='cp65001'>
-
打开文件
with open('em.txt', 'w') as f: f.write('ememem')
-
线程lock
lock = threading.Lock() # with里面获取lock, 退出with后释放lock with 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, sys from contextlib import closing with closing(urllib.urlopen('http://www.yahoo.com')) as f: for line in f: sys.stdout.write(line)