python中的with語句使用於對資源進行訪問的場合,在程式處理過程中是否異常都會執行__enter__(self)方法,exit(『清理』)方法操作,釋放被訪問的資源,比如有檔案讀寫後自動關閉、執行緒中鎖的自動獲取和釋放都可以使用。
用open開啟乙個檔案進行讀寫時,都有可能產生ioerror。而且檔案每次使用完畢後必須關閉,因為檔案物件會占用作業系統的資源,並且作業系統同一時間能開啟的檔案數量也是有限的,python引入with語句來自動幫我們呼叫close()方法和預防異常。
#檔案的寫
with open('/users/bright/test.txt', 'w') as f:
f.write('hello, world!')
#檔案的讀取
with open('/users/bright/test.txt', 'r') as f:
print(f.read())
基本思想是with所求值的物件必須有乙個__enter__()方法,乙個__exit__()方法。緊跟with後面的語句被求值後,import threading
import time
#全域性變數多個執行緒可以讀寫,傳遞資料
mutex_num=0
mutex=threading.lock() #建立乙個鎖
class mythread(threading.thread):
def run(self):
global mutex_num
with mutex: # with lock的作用相當於自動獲取和釋放鎖
for i in range(8800000): #鎖定期間,其他執行緒不可以幹活
mutex_num+=1
#上面3行的和下面3行的**是等價的
# if mutex.acquire(1):#上鎖成功往下執行,沒有鎖住就一直等待,1代表獨佔
# for i in range(8800000): #鎖定期間,其他執行緒不可以執行任務
# mutex_num+=1
# mutex.release() #釋放鎖
print(mutex_num)
mythread=
for i in range(3):
t=mythread()
t.start()
for t in mythread:
t.join()
print("threading end.........")
返回物件的__enter__()方法被呼叫,這個方法的返回值將被賦值給as後面的變數。當with後面的**塊全部被執行完之後,將呼叫前面返回物件的__exit__()方法。with真正強大之處是它可以處理異常。他的__exit__方法有三個引數val,type 和 trace,這些引數在異常處理中相當有用。
class sample:
def __enter__(self):
# __enter__()方法首先被執行
print(self)
return self
def __exit__(self, type, value, trace):
#函式執行結束,最後__exit__()方法被呼叫
print "type:", type
print "value:", value
print "trace:", trace
def run(self):
num = 1/0
# num = 1
# num = 1時,<__main__.sample instance at 0x024838c8>
# type: none
# value: none
# trace: none
return num
# __enter__()方法返回的值 ,賦值給變數』sample』
with sample() as sample:
sample.run()
# <__main__.sample instance at 0x025638c8>
# type: # value: integer division or modulo by zero
# trace: # traceback (most recent call last):
# file "e:/data/it/project/withtext.py", line 66, in # sample.run()
# file "e:/data/it/project/withtext.py", line 61, in run
# num = 1/0
# zerodivisionerror: integer division or modulo by zero
Pytho高階篇 yield的用法
yield 是python中非常有用的乙個關鍵字,可以實現很多魔法。yield關鍵字主要有一下幾個用法。1.yield基本用法 yield用在函式中,實現類似用return的功能,但是返回的是乙個generator.更多詳細解釋,參考下邊的 如何正確理解yiled在函式中的作用 2.yield實現上...
mysql中的if條件語句用法
if expr1,expr2,expr3 如果 expr1 是true expr1 0 and expr1 null 則 if 的返回值為 expr2 否則返回值則為 expr3 if 的返回值為數字值或字串值,具體情況視其所在語境而定。mysql select if 1 2,2,3 3 mysql...
巨集定義中if語句的用法
當巨集定義中含有 if 時 1 定義如下巨集 define dc p if foo p fun p 用在下面的環境中 if k n dc k else dc n 巨集替換後,如下 if k n if foo k fun k else if foo n fun n 可見,原來的 if 和 else 不...