深入浅析python with语句简介

yipeiwu_com5年前Python基础

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设计】网站的支持!

相关文章

Python(Django)项目与Apache的管理交互的方法

Python(Django)项目与Apache的管理交互的方法

准备:Django的环境(Python)、Apache、Wsgi(必须文件) 首先需要电脑有Python基础下并且安装好Django的环境,下载Apache文件和Wsgi文件。 Apac...

解决python 文本过滤和清理问题

问题 某些无聊的脚本小子在Web页面表单中填入了“pýtĥöñ”这样的文本,我们想以某种方式将其清理掉。 解决方案 文本过滤和清理所涵盖的...

浅述python中深浅拷贝原理

前言 在c++中参数传递有两种形式:值传递和引用传递。这两种方式的区别我不在此说,自行补上,如果你不知道的话。我先上python代码,看完我们总结一下,代码如下: # copy m...

python实现机器学习之多元线性回归

python实现机器学习之多元线性回归

总体思路与一元线性回归思想一样,现在将数据以矩阵形式进行运算,更加方便。 一元线性回归实现代码 下面是多元线性回归用Python实现的代码: import numpy as np...

Python统计文件中去重后uuid个数的方法

本文实例讲述了Python统计文件中去重后uuid个数的方法。分享给大家供大家参考。具体如下: 利用正则表达式按行获取日志文件中的的uuid,并且统计这些uuid的去重个数(去重利用se...