深入浅析python with语句简介


Posted in Python onApril 11, 2018

with 语句是从 Python 2.5 开始引入的一种与异常处理相关的功能(2.5 版本中要通过 from __future__ import with_statement 导入后才可以使用),从 2.6 版本开始缺省可用(参考 What's new in Python 2.6? 中 with 语句相关部分介绍)。with 语句适用于对资源进行访问的场合,确保不管使用过程中是否发生异常都会执行必要的“清理”操作,释放资源,比如文件使用后自动关闭、线程中锁的自动获取和释放等。

术语

要使用 with 语句,首先要明白上下文管理器这一概念。有了上下文管理器,with 语句才能工作。

在python中读写操作资源,最后需要释放资源。可以使用try…finally结构实现资源的正确释放,python提供了一个with语句能更简便的实现释放资源。

1. python像文件的操作open等已经可以直接使用with语句

2. 可以自定义一个支持with语句对象

3. 使用contextlib也可以使用with语句对象

4. 针对需要close操作的对象with的使用

示例代码中有4种使用标注

# 自定义支持with语句的对象
class DummyRes:
  def __init__(self, tag):
    self.tag = tag
  def __enter__(self):
    print("Enter >>> {}".format(self.tag))
    return self
  def __exit__(self, exc_type, exc_value, exc_tb):
    print("Exit <<< {}".format(self.tag))
    if exc_tb is None:
      print("Exit without Exception {}".format(self.tag))
      return False
    else:
      print("Exit with Exception {}".format(self.tag))
      return True
# 支持closing 上下文with语句对象
class Closing:
  def __init__(self, thing):
    self.thing = thing
  def __enter__(self):
    return self
  def __exit__(self, exc_type, exc_value, exc_tb):
    self.thing.close()
class ClosingDemo:
  def __init__(self):
    self.acquire()
  def acquire(self):
    print("Acquire RES")
  def close(self):
    print("Close RES")
from contextlib import contextmanager
class ContextDemo:
  def __init__(self):
    print("Context Demo init")
    raise Exception
    print("Context Demo init")
  def print(self):
    print("Context Demo print 1")
    #raise Exception
    print("Context Demo print 2")
  def close(self):
    print("Context Demo close")
def context_demo():
  print("context demo in")
  raise Exception
  print("context demo out")
@contextmanager
def demo():
  print("Allocate Resoures")
  try:
    yield context_demo
  finally:
    print("raise exception")
  #yield "*** contextmanager demo ***"
  print("Free Resoures")
if __name__ == "__main__":
  # 1. 使用with语句 (自动关闭文件)
  with open("test.txt", "w") as f:
    f.write("write test")
  # 2. 自动定义with语句
  with DummyRes("test") as res:
    print("With body 1")
    raise Exception
    print("With body 2")
  # 3. 利用contextlib定义with语句
  with demo():
    print("exc demo")
  # 4. closing 上下文 (适合有close操作的情况)
  with Closing(ClosingDemo()):
    print("Use Resoures")

总结

以上所述是小编给大家介绍的python with语句简介,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!

Python 相关文章推荐
web.py在模板中输出美元符号的方法
Aug 26 Python
基于Python如何使用AIML搭建聊天机器人
Jan 27 Python
python 计算一个字符串中所有数字的和实例
Jun 11 Python
Django ORM 自定义 char 类型字段解析
Aug 09 Python
python 实现保存最新的三份文件,其余的都删掉
Dec 22 Python
python已协程方式处理任务实现过程
Dec 27 Python
tensorflow指定GPU与动态分配GPU memory设置
Feb 03 Python
python GUI库图形界面开发之PyQt5窗口类QMainWindow详细使用方法
Feb 26 Python
Python OpenCV实现测量图片物体宽度
May 27 Python
15个应该掌握的Jupyter Notebook使用技巧(小结)
Sep 23 Python
python绕过图片滑动验证码实现爬取PTA所有题目功能 附源码
Jan 06 Python
django上传文件的三种方式
Apr 29 Python
python实现微信自动回复功能
Apr 11 #Python
Python实现检测文件MD5值的方法示例
Apr 11 #Python
python 输出上个月的月末日期实例
Apr 11 #Python
Python简单计算文件MD5值的方法示例
Apr 11 #Python
pandas 获取季度,月度,年度首尾日期的方法
Apr 11 #Python
python+pandas生成指定日期和重采样的方法
Apr 11 #Python
python dataframe astype 字段类型转换方法
Apr 11 #Python
You might like
PHP常用技巧总结(附函数代码)
2012/02/04 PHP
强烈声明: 不要使用(include/require)_once
2013/06/06 PHP
php实现表单多按钮提交action的处理方法
2015/10/24 PHP
PHP遍历目录文件的常用方法小结
2017/02/03 PHP
PHP实现的观察者模式实例
2017/06/21 PHP
js中cookie的使用详细分析
2008/05/28 Javascript
jQuery学习4 浏览器的事件模型
2010/02/07 Javascript
javascript数组去掉重复
2011/05/12 Javascript
javascript scrollTop正解使用方法
2013/11/14 Javascript
浅谈js的setInterval事件
2014/12/05 Javascript
jQuery实现Meizu魅族官方网站的导航菜单效果
2015/09/14 Javascript
利用Node.js制作爬取大众点评的爬虫
2016/09/22 Javascript
微信小程序出现wx.navigateTo页面不跳转问题的解决方法
2017/12/26 Javascript
微信小程序实现的点击按钮 弹出底部上拉菜单功能示例
2018/12/20 Javascript
python 自动提交和抓取网页
2009/07/13 Python
python操作gmail实例
2015/01/14 Python
Python端口扫描简单程序
2016/11/10 Python
Python定义二叉树及4种遍历方法实例详解
2018/07/05 Python
在Python中获取两数相除的商和余数方法
2018/11/10 Python
Python正则匹配判断手机号是否合法的方法
2020/12/09 Python
Python图像的增强处理操作示例【基于ImageEnhance类】
2019/01/03 Python
python 用 xlwings 库 生成图表的操作方法
2019/12/22 Python
Python实现大数据收集至excel的思路详解
2020/01/03 Python
美国从事品牌鞋类零售的连锁店:Famous Footwear
2016/08/25 全球购物
拉斯维加斯酒店、演出、旅游、俱乐部及更多:Vegas.com
2019/02/28 全球购物
美国在线购买和出售礼品卡网站:EJ Gift Cards
2019/06/09 全球购物
在加拿大在线租赁和购买电子游戏:Game Access
2019/09/02 全球购物
EJB包括(SessionBean,EntityBean)说出他们的生命周期,及如何管理事务的?
2013/02/17 面试题
外贸学院会计专业应届生求职信
2013/11/14 职场文书
好的演讲稿开场白
2013/12/30 职场文书
小学教师师德演讲稿
2014/05/06 职场文书
党员批评与自我批评范文
2014/09/23 职场文书
2014年物业公司工作总结
2014/11/22 职场文书
2015年国庆节活动总结
2015/03/23 职场文书
Python 机器学习工具包SKlearn的安装与使用
2021/05/14 Python
MySQL数据库10秒内插入百万条数据的实现
2021/11/01 MySQL