脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python 上下文管理器使用方法小结

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

2020-12-11 00:07苟雨 Python

本文介绍了Python中的上下文管理器,以及如何结合with语句来使用上下文管理器,并且总结了一下with 语句的执行流程。在很多情况下,with语句可以简化代码,并增加代码的健壮性。

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

?
1
2
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语句不仅可以管理文件,还可以管理锁、连接等等,如,

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#管理锁
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来处理异常。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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提供了更简单的写法,

基本语法

?
1
2
3
4
5
6
7
@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函数返回。
例,
自动加括号

?
1
2
3
4
5
6
7
8
9
10
11
12
13
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')

管理锁

?
1
2
3
4
5
6
7
8
9
10
11
12
@contextmanager
def locked(lock):
  lock.acquire()
  try:
    yield
  finally:
    lock.release()
 
with locked(myLock):
  #代码执行到这里时,myLock已经自动上锁
  pass
  #执行完后会,会自动释放锁

管理文件关闭

?
1
2
3
4
5
6
7
8
9
10
11
@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)

管理数据库回滚

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@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():

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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()

嵌套使用

?
1
2
3
4
5
6
7
8
9
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

原文链接:http://www.jianshu.com/p/1665225b8231

延伸 · 阅读

精彩推荐