python -with用法
2014-10-25 12:24
344 查看
#coding=utf-8 with open(r'bm.py') as somefile: for line in somefile: print line # ...more code #这里使用了 with 语句,不管在处理文件过程中是否发生异常,都能保证 with 语句执行完毕后 #已经关闭了打开的文件句柄。如果使用传统的 try/finally 范式,则要使用类似如下代码: somefile = open(r'bm.py') try: for line in somefile: print line # ...more code finally: somefile.close()
装饰器 contextmanager
contextmanager 用于对生成器函数进行装饰,生成器函数被装饰以后,返回的是一个上下文管理器,其 __enter__() 和 __exit__() 方法由 contextmanager 负责提供,而不再是之前的迭代子。被装饰的生成器函数只能产生一个值,否则会导致异常 RuntimeError;产生的值会赋值给 as 子句中的 target,如果使用了 as 子句的话。下面看一个简单的例子。
清单 9. 装饰器 contextmanager 使用示例
from contextlib import contextmanager
@contextmanager
def demo():
print '[Allocate resources]'
print 'Code before yield-statement executes in __enter__'
yield '*** contextmanager demo ***'
print 'Code after yield-statement executes in __exit__'
print '[Free resources]'
with demo() as value:
print 'Assigned Value: %s' % value
相关文章推荐
- python with语句的用法
- python学习:异常处理、with用法以及utf8中文显示
- python中with和contextlib的用法
- Python中with...as的用法
- 详解Python中with语句的用法
- python with...as...用法
- python with用法
- 学习Python:with...as的用法
- python的with用法
- Python中的with...as用法介绍
- python中关于with及contextlib的用法
- Python with语句用法
- 【ZZ】python with...as...用法
- Python的with...as的用法
- Python with的用法
- python中关于with及contextlib的用法
- python中with的用法
- python 中关于with...as的用法
- python with...as...用法
- python with...as...用法