• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
孙龙 程序员
少时总觉为人易,华年方知立业难
博客园    首页    新随笔    联系   管理    订阅  订阅
with上下文管理协议以及contextlib
 1 #try except finally
 2 def exe_try():
 3     try:
 4         print ("code started")
 5         raise KeyError
 6         return 1
 7     except KeyError as e:
 8         print ("key error")
 9         return 2
10     else:
11         print ("other error")
12         return 3
13     finally:
14         print ("finally")
15         # return 4
16 
17 #上下文管理器协议
18 class Sample:
19     def __enter__(self):
20         print ("enter")
21         #获取资源
22         return self
23     def __exit__(self, exc_type, exc_val, exc_tb):
24         #释放资源
25         print ("exit")
26     def do_something(self):
27         print ("doing something")
28 
29 with Sample() as sample:
30     sample.do_something()
31 
32 # if __name__ == "__main__":
33 #     result = exe_try()
34 #     print (result)

 

 1 import contextlib
 2 
 3 @contextlib.contextmanager
 4 def file_open(file_name):
 5     print ("file open")
 6     yield {}
 7     print ("file end")
 8 
 9 with file_open("bobby.txt") as f_opened:
10     print ("file processing")

 

本文来自博客园,作者:孙龙-程序员,转载请注明原文链接:https://www.cnblogs.com/sunlong88/articles/9368907.html

posted on 2018-07-25 23:06  孙龙-程序员  阅读(159)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3