with高階# coding:utf8
def except_try():
try:
print("start")
#raise keyerror
raise indexerror
return 1
except keyerror:
print("key error 異常時執行")
return 2
else:
print("other error")
return 3
finally:
print("總會執行")
return 4
# 上下文管理協議
class withdemo:
def __enter__(self):
print("呼叫with開始時執行")
# return self
# 獲取資源
def __exit__(self, exc_type, exc_val, exc_tb):
print("呼叫with結束時執行")
#用於釋放資源
def do_something(self):
print("do something")
if __name__ == '__main__':
try:
print("start")
raise keyerror
# raise indexerror
except keyerror:
print("key error 異常時執行")
else:
print("other error")
finally:
print("總會執行")
# return 壓棧
print(except_try()) #4
print("********************with********************")
with withdemo() as wd:
wd.do_something()
# coding:utf8
import contextlib
@contextlib.contextmanager
def write_file(file):
print(file," file open")
print("檔案操作中。。。") # 最先執行
# raise ioerror
yield {}
print("file close") #最後執行
if __name__ == '__main__':
with write_file("/usr/local/data/test") as f:
print("start...")
Python with用法 自動關閉檔案原理
with語句的語法,ontext expression 用於建立可自動關閉的資源。with context expression as target s with 塊 使用with 開啟檔案並讀取檔案資料 with open test.yml encoding utf 8 as f print f,...
關於python with的用法及異常處理
在網上看到一些人部落格使用 with 用於異常處理,但是我在網仔細查閱,發現 該關鍵字不是用於處理異常的。實際上,在with後面的 塊丟擲異常時,exit 方法被執行。開發庫時,清理資源,關閉檔案等操作,都可以放在exit 方法中。總之,with as表示式極大的簡化了每次寫finally的工作,這...
python with 語句研究
import sys class test def enter self print enter return 1 def exit self,args print exit return true with test as t print t is not the result of test i...