我试图在Python3.3中使用架架。建议使用with shelve.open('spam.db') as db:...语法来确保关闭“连接”。但是,当我尝试时,我会得到以下错误AttributeError: __exit__。怎么回事?有什么想法吗?这里有许多类似的问题,虽然找不到令人满意的解决办法。以下是我迄今所作的尝试:
下列情况失败:
import shelve
with shelve.open('spam.db') as db:
db['key'] = 'value'
print(db['key'])错误消息:
Traceback (most recent call last):
File "D:\arbitrary_path_to_script\nf_shelve_test.py", line 3, in <module>
with shelve.open('spam.db') as db:
AttributeError: __exit__
[Finished in 0.1s with exit code 1]以下工作:
import shelve
db = shelve.open('spam.db')
db['key'] = 'value'
print(db['key'])
db.close()和预期产出:
value
[Finished in 0.1s]打印搁置模块路径
import shelve
print(shelve)位置:
<module 'shelve' from 'C:\\Python33\\lib\\shelve.py'>
[Finished in 0.1s]发布于 2015-05-25 18:26:28
在Python3.3中,shelve.open()不是上下文管理器,不能在with语句中使用。with语句期望存在方法;您看到的错误是因为没有这样的方法。
您可以在这里使用contextlib.closing()将shelve.open()结果包装在上下文管理器中:
from contextlib import closing
with closing(shelve.open('spam.db')) as db:或者,升级到Python3.4,其中所需的上下文管理器方法被添加到shelve.open()的返回值中。来自文档
在3.4版中更改:添加上下文管理器支持。
发布于 2015-05-25 18:27:00
Shelf不是Python3.3中的上下文管理器;这个功能是在3.4中引入的。如果需要支持3.3,则需要在finally块中使用contextlib.closing或显式close。我推荐contextlib.closing。
import contextlib
with contextlib.closing(shelve.open('spam.db')) as db:
do_whatever_with(db)https://stackoverflow.com/questions/30444019
复制相似问题