上下文管理器最常用的是確保正確關閉文件,
with open('/path/to/file', 'r') as f:
f.read()
with 語句的基本語法,
with expression [as variable]:
with-block
expression是一個上下文管理器,其實現了enter和exit兩個函數。當我們調用一個with語句時, 依次執行一下步驟,
1.首先生成一個上下文管理器expression, 比如open('xx.txt').
2.執行expression.enter()。如果指定了[as variable]說明符,將enter()的返回值賦給variable.
3.執行with-block語句塊.
4.執行expression.exit(),在exit()函數中可以進行資源清理工作.
with語句不僅可以管理文件,還可以管理鎖、連接等等,如,
#管理鎖
import threading
lock = threading.lock()
with lock:
#執行一些操作
pass
#數據庫連接管理
def test_write():
sql = """ #具體的sql語句
"""
con = DBConnection()
with con as cursor:
cursor.execute(sql)
cursor.execute(sql)
cursor.execute(sql)
自定義上下文管理器
上下文管理器就是實現了上下文協議的類 ,也就是要實現 __enter__()
和__exit__()
兩個方法。
__enter__()
:主要執行一些環境準備工作,同時返回一資源對象。如果上下文管理器open("test.txt")的enter()函數返回一個文件對象。
__exit__()
:完整形式為exit(type, value, traceback),這三個參數和調用sys.exec_info()函數返回值是一樣的,分別為異常類型、異常信息和堆棧。如果執行體語句沒有引發異常,則這三個參數均被設為None。否則,它們將包含上下文的異常信息。_exit()方法返回True或False,分別指示被引發的異常有沒有被處理,如果返回False,引發的異常將會被傳遞出上下文。如果exit()函數內部引發了異常,則會覆蓋掉執行體的中引發的異常。處理異常時,不需要重新拋出異常,只需要返回False,with語句會檢測exit()返回False來處理異常。
class test_query:
def __init__(self):
pass
def query(self):
print('query')
def __enter__(self):
# 如果是數據庫連接就可以返回cursor對象
# cursor = self.cursor
# return cursor
print('begin query,')
return self #由于這里沒有資源對象就返回對象
def __exit__(self,exc_type,exc_value,traceback):
if traceback is None:
print('End')
else:
print('Error')
# 如果是數據庫連接提交操作
# if traceback is None:
# self.commit()
# else:
# self.rollback()
if __name__ == '__main__':
with test_query() as q:
q.query()
contextlib
編寫enter和exit仍然很繁瑣,因此Python的標準庫contextlib提供了更簡單的寫法,
基本語法
@contextmanager
def some_generator(<arguments>):
<setup>
try:
yield <value>
finally:
<cleanup>
生成器函數some_generator就和我們普通的函數一樣,它的原理如下:
some_generator函數在在yield之前的代碼等同于上下文管理器中的enter函數.
yield的返回值等同于enter函數的返回值,即如果with語句聲明了as <variable>,則yield的值會賦給variable.
然后執行<cleanup>代碼塊,等同于上下文管理器的exit函數。此時發生的任何異常都會再次通過yield函數返回。
例,
自動加括號
import contextlib
@contextlib.contextmanager
def tag(name):
print('<{}>'.format(name))
yield
print('</{}>'.format(name))
if __name__ == '__main__':
with tag('h1') as t:
print('hello')
print('context')
管理鎖
@contextmanager
def locked(lock):
lock.acquire()
try:
yield
finally:
lock.release()
with locked(myLock):
#代碼執行到這里時,myLock已經自動上鎖
pass
#執行完后會,會自動釋放鎖
管理文件關閉
@contextmanager
def myopen(filename, mode="r"):
f = open(filename,mode)
try:
yield f
finally:
f.close()
with myopen("test.txt") as f:
for line in f:
print(line)
管理數據庫回滾
@contextmanager
def transaction(db):
db.begin()
try:
yield
except:
db.rollback()
raise
else:
db.commit()
with transaction(mydb):
mydb.cursor.execute(sql)
mydb.cursor.execute(sql)
mydb.cursor.execute(sql)
mydb.cursor.execute(sql)
這就很方便!
如果一個對象沒有實現上下文,我們就不能把它用于with語句。這個時候,可以用closing()
來把該對象變為上下文對象。它的exit函數僅僅調用傳入參數的close函數.
例如,用with語句使用urlopen():
import contextlib
from urllib.request import urlopen
if __name__ == '__main__':
with contextlib.closing(urlopen('https://www.python.org')) as page:
for line in page:
print(line)
closing也是一個經過@contextmanager裝飾的generator,這個generator編寫起來其實非常簡單:
@contextmanager
def closing(thing):
try:
yield thing
finally:
thing.close()
嵌套使用
import contextlib
from urllib.request import urlopen
if __name__ == '__main__':
with contextlib.closing(urlopen('https://www.python.org')) as page,\
contextlib.closing(urlopen('https://www.python.org')) as p:
for line in page:
print(line)
print(p)
在2.x中需要使用contextlib.nested()
才能使用嵌套,3.x中可以直接使用。
更多函數可以參考官方文檔https://docs.python.org/3/library/contextlib.html