contextlib
contextlib
with 语句 上下文
任何对象,只要正确实现了上下文管理,就可以用于with语句。
实现上下文管理是通过__enter__和__exit__这两个方法实现的。
例如,下面的class实现了这两个方法:
class Query(object):
def __init__(self, name):
self.name = name
def __enter__(self):
print('Begin')
return self
def __exit__(self, exc_type, exc_value, traceback):
if exc_type:
print('Error')
else:
print('End')
def query(self):
print('Query info about %s...' % self.name)
就可以把自己写的资源对象用于with语句:
with Query('Bob') as q:
q.query()
编写__enter__和__exit__仍然很繁琐,因此Python的标准库contextlib提供了更简单的写法,上面的代码可以改写如下:
from contextlib import contextmanager
class Query(object):
def __init__(self, name):
self.name = name
def query(self):
print('Query info about %s...' % self.name)
@contextmanager
def create_query(name):
print('Begin')
q = Query(name)
yield q
print('End')
@contextmanager这个decorator接受一个generator
在某段代码执行前后自动执行特定代码,也可以用@contextmanager实现。例如:
@contextmanager
def tag(name):
print("<%s>" % name)
yield
print("</%s>" % name)
with tag("h1"):
print("hello")
print("world")
上述代码执行结果为:
<h1>
hello
world
</h1>
with语句首先执行yield之前的语句,因此打印出<h1>;
yield调用会执行with语句内部的所有语句,因此打印出hello和world;
最后执行yield之后的语句,打印出</h1>。
可以用closing()来把该对象变为上下文对象。例如,用with语句使用urlopen():
from contextlib import closing
from urllib.request import urlopen
with closing(urlopen('https://www.python.org')) as page:
for line in page:
print(line)
closing也是一个经过@contextmanager装饰的generator
它的作用就是把任意对象变为上下文对象,并支持with语句。
contextlib的更多相关文章
- RF源码阅读(碎片纪录)-Python积木之contextlib
参考页面: http://docs.python.org/2/library/contextlib.html contextlib是为了配合with语句来使用的.使用起来更加简洁.本来想写一下,这位同 ...
- python contextlib 上下文管理器
1.with操作符 在python中读写文件,可能需要这样的代码 try-finally读写文件 file_text = None try: file_text = open('./text', 'r ...
- 【Python】 上下文管理器和contextlib
上下文管理器 一直对python中的上下文管理比较迷惑,趁着今天研究SQLAlchemy顺便看了一下,感觉稍微清楚了一点.http://www.cnblogs.com/chenny7/p/421344 ...
- python上下文管理器ContextLib及with语句
http://blog.csdn.net/pipisorry/article/details/50444736 with语句 with语句是从 Python 2.5 开始引入的一种与异常处理相关的功能 ...
- Python with/as和contextlib上下文管理使用说明
with/as 使用open打开过文件的对with/as都已经非常熟悉,其实with/as是对try/finally的一种替代方案. 当某个对象支持一种称为"环境管理协议"的协议时 ...
- 一分钟了解contextlib模块
cobtextlib模块用于简化上下文管理器,其内置装饰漆@contextmanager,我们通过编写一个被contextmanager装饰的generator来简化上下文管理. from conte ...
- python常用内建模块 collections,bs64,struct,hashlib,itertools,contextlib,xml
# 2 collections 是Python内建的一个集合模块,提供了许多有用的集合类. # 2.1 namedtuple #tuple可以表示不变集合,例如,一个点的二维坐标就可以表示成: p ...
- contextlib 上下文管理器
在Python中,读写文件这样的资源要特别注意,必须在使用完毕后正确关闭它们.正确关闭文件资源的一个方法是使用try...finally: try: f = open('/path/to/file', ...
- (转)contextlib — 上下文管理器工具
原文:https://pythoncaff.com/docs/pymotw/contextlib-context-manager-tool/95 这是一篇社区协同翻译的文章,你可以点击右边区块信息里的 ...
- python之模块contextlib 加强with语句而存在
# -*- coding: utf-8 -*- #python 27 #xiaodeng #python之模块contextlib,为加强with语句而存在 #特别注意:python3和python2 ...
随机推荐
- nginx故障分析与记录
本文是对于自己遇到nginx故障的一些记录.便于以后解决问题. 时间:2018_05_11 场景一:某天很多客户在群里反应说访问网站不了,报504错误. 环境:首先说明一点的就是公司网站是美国,日本等 ...
- memcached 学习笔记 4
memcached真实项目中的应用 1 缓存式的Web应用程序架构 有了缓存的支持,我们可以在传统的app层和db层之间加入cache层,每个app服务器都可以绑定一个mc, 每次数据的读取都可以从m ...
- oracle 数据库添加Java方法
create or replace and compile java source named "Bitconverter" aspublic class Bitconverter ...
- 清空控件的TeXt属性
foreach (Control item in groupBox1.Controls) { if (item is TextBox) //判断控件是不是TextBox { item.Text = & ...
- android 使用图片轮播图---banner 使用
转自:https://github.com/youth5201314/banner 使用步骤 Step 1.依赖banner Gradle dependencies{ compile 'com.you ...
- iptables-linux(ls)-inode-block
Part1:iptables 环境:centos6.7 目前我只配置了INPUT.OUTPUT和FORWORD都是ACCEPT的规则 由于想要先实现防火墙规则,所以前面的内容讲的是方法,后面是详解ip ...
- org.apache.commons.lang.StringUtils
org.apache.commons.lang.StringUtils 作为jdk中lang包的补充 检查CharSequence是否为空,null或者空格 CharSequence (CharBuf ...
- Exception in thread "main" java.nio.channels.NotYetConnectedException
import java.nio.channels.AsynchronousServerSocketChannel; import java.nio.channels.AsynchronousSocke ...
- PowerDesigner16使用方法
网上下载一个破解版的PowerDesigner https://www.cnblogs.com/longshiyVip/p/4643871.html 1.新建一个Physical Data Model ...
- 《JavaWeb从入门到改行》fileupload,没毛病
目录: » fileupload API > 文件上传的要求 > fileupload组件 » 上传细节的代码演示 » 项目案例-上传头像并显示 fileupload API 文 ...