python 上下文管理器使用方法小结

yipeiwu_com7年前Python基础

上下文管理器最常用的是确保正确关闭文件,

with open('/path/to/file', 'r') as f:
 f.read()


with 语句的基本语法,

with expression [as variable]:
    with-block

expression是一个上下文管理器,其实现了enter和exit两个函数。当我们调用一个with语句时, 依次执行一下步骤,

1.首先生成一个上下文管理器expression, 比如open('xx.txt').
2.执行expression.enter()。如果指定了[as variable]说明符,将enter()的返回值赋给variable.
3.执行with-block语句块.
4.执行expression.exit(),在exit()函数中可以进行资源清理工作.

with语句不仅可以管理文件,还可以管理锁、连接等等,如,

#管理锁
import threading
lock = threading.lock()
with lock:
 #执行一些操作
 pass

#数据库连接管理
def test_write():
 sql = """  #具体的sql语句
 """
 con = DBConnection()
 with con as cursor: 
  cursor.execute(sql)
  cursor.execute(sql)
  cursor.execute(sql)

自定义上下文管理器

上下文管理器就是实现了上下文协议的类 ,也就是要实现 __enter__()和__exit__()两个方法。

__enter__():主要执行一些环境准备工作,同时返回一资源对象。如果上下文管理器open("test.txt")的enter()函数返回一个文件对象。
__exit__():完整形式为exit(type, value, traceback),这三个参数和调用sys.exec_info()函数返回值是一样的,分别为异常类型、异常信息和堆栈。如果执行体语句没有引发异常,则这三个参数均被设为None。否则,它们将包含上下文的异常信息。_exit()方法返回True或False,分别指示被引发的异常有没有被处理,如果返回False,引发的异常将会被传递出上下文。如果exit()函数内部引发了异常,则会覆盖掉执行体的中引发的异常。处理异常时,不需要重新抛出异常,只需要返回False,with语句会检测exit()返回False来处理异常。

class test_query:
  def __init__(self):
    pass

  def query(self):
    print('query')

  def __enter__(self):
    # 如果是数据库连接就可以返回cursor对象
    # cursor = self.cursor
    # return cursor
    print('begin query,')
    return self #由于这里没有资源对象就返回对象
    
  def __exit__(self,exc_type,exc_value,traceback):
    if traceback is None:
      print('End')
    else:
      print('Error')

    # 如果是数据库连接提交操作
    # if traceback is None:
    #  self.commit()
    # else:
    #  self.rollback()
    
if __name__ == '__main__':
  with test_query() as q:
    q.query()

contextlib

编写enter和exit仍然很繁琐,因此Python的标准库contextlib提供了更简单的写法,

基本语法

  @contextmanager
    def some_generator(<arguments>):
      <setup>
      try:
        yield <value>
      finally:
        <cleanup>

生成器函数some_generator就和我们普通的函数一样,它的原理如下:
some_generator函数在在yield之前的代码等同于上下文管理器中的enter函数.
yield的返回值等同于enter函数的返回值,即如果with语句声明了as <variable>,则yield的值会赋给variable.
然后执行<cleanup>代码块,等同于上下文管理器的exit函数。此时发生的任何异常都会再次通过yield函数返回。
例,
自动加括号

import contextlib

@contextlib.contextmanager
def tag(name):
  print('<{}>'.format(name))
  yield
  print('</{}>'.format(name))


if __name__ == '__main__':
  with tag('h1') as t:
    print('hello')
    print('context')

管理锁

@contextmanager
def locked(lock):
  lock.acquire()
  try:
    yield
  finally:
    lock.release()

with locked(myLock):
  #代码执行到这里时,myLock已经自动上锁
  pass
  #执行完后会,会自动释放锁

管理文件关闭

@contextmanager
def myopen(filename, mode="r"):
  f = open(filename,mode)
  try:
    yield f
  finally:
    f.close()

with myopen("test.txt") as f:
  for line in f:
    print(line)

管理数据库回滚

@contextmanager
def transaction(db):
  db.begin()
  try:
    yield 
  except:
    db.rollback()
    raise
  else:
    db.commit()

with transaction(mydb):
  mydb.cursor.execute(sql)
  mydb.cursor.execute(sql)
  mydb.cursor.execute(sql)
  mydb.cursor.execute(sql)

这就很方便!
如果一个对象没有实现上下文,我们就不能把它用于with语句。这个时候,可以用closing()来把该对象变为上下文对象。它的exit函数仅仅调用传入参数的close函数.
例如,用with语句使用urlopen():

import contextlib
from urllib.request import urlopen

if __name__ == '__main__':
  with contextlib.closing(urlopen('https://www.python.org')) as page:
    for line in page:
      print(line)
closing也是一个经过@contextmanager装饰的generator,这个generator编写起来其实非常简单:

@contextmanager
def closing(thing):
  try:
    yield thing
  finally:
    thing.close()

嵌套使用

import contextlib
from urllib.request import urlopen

if __name__ == '__main__':
  with contextlib.closing(urlopen('https://www.python.org')) as page,\
      contextlib.closing(urlopen('https://www.python.org')) as p:
    for line in page:
      print(line)
        print(p)

在2.x中需要使用contextlib.nested()才能使用嵌套,3.x中可以直接使用。

更多函数可以参考官方文档https://docs.python.org/3/library/contextlib.html

相关文章

探究python中open函数的使用

探究python中open函数的使用

最近,开始学习python的开发,遇到了一点文件操作的问题,探究一下open函数的使用。 一、open()的函数原型 open(file, mode=‘r', buffering=-1,...

Python的Urllib库的基本使用教程

Python的Urllib库的基本使用教程

1.分分钟扒一个网页下来 怎样扒网页呢?其实就是根据URL来获取它的网页信息,虽然我们在浏览器中看到的是一幅幅优美的画面,但是其实是由浏览器解释才呈现出来的,实质它 是一段HTML代码,...

Python 中 Virtualenv 和 pip 的简单用法详解

本文介绍了Python 中 Virtualenv 和 pip 的简单用法详解,分享给大家,具体如下: 0X00 安装环境 我们在 Python 开发和学习过程中需要用到各种库,然后在各个...

使用Rasterio读取栅格数据的实例讲解

Rasterio简介 有没有觉得用GDAL的Python绑定书写的代码很不Pythonic,强迫症的你可能有些忍受不了。不过,没关系,MapBox旗下的开源库Rasterio帮我们解决了...

python实现日常记账本小程序

python实现收支的自动计算,能够查询每笔账款的消费详情,具体内容如下 1、函数需要两个文件:一个类似钱包功能,存放钱;另一个用于记录每笔花销的用途 #!/usr/bin/env...