【发布时间】:2013-03-16 08:19:15
【问题描述】:
在我的代码中,我需要能够正确打开和关闭设备,因此需要使用上下文管理器。虽然上下文管理器通常被定义为具有__enter__ 和__exit__ 方法的类,但似乎也可以装饰一个函数以与上下文管理器一起使用(参见a recent post 和another nice example here)。
在以下(工作)代码 sn-p 中,我实现了两种可能性;只需要将注释行与另一行交换即可:
import time
import contextlib
def device():
return 42
@contextlib.contextmanager
def wrap():
print("open")
yield device
print("close")
return
class Wrap(object):
def __enter__(self):
print("open")
return device
def __exit__(self, type, value, traceback):
print("close")
#with wrap() as mydevice:
with Wrap() as mydevice:
while True:
time.sleep(1)
print mydevice()
我尝试运行代码并使用CTRL-C 停止它。当我在上下文管理器中使用Wrap 类时,__exit__ 方法被调用为预期的(文本'close' 打印在终端中),但是当我用wrap 函数尝试同样的事情时,文本“关闭”不会打印到终端。
我的问题:代码 sn-p 是否有问题,我是否遗漏了什么,或者为什么没有使用装饰函数调用行 print("close")?
【问题讨论】:
标签: python python-2.7 contextmanager