Shelve使用“with Shelve.open”语法在Python3.3中为hello world示例提供AttributeError,但不能没有它

Shelve使用“with Shelve.open”语法在Python3.3中为hello world示例提供AttributeError,但不能没有它,python,python-3.x,with-statement,shelve,Python,Python 3.x,With Statement,Shelve,我正在尝试使用Python3.3。建议与搁置一起使用。将“spam.db”打开为db:。。。确保我们关闭连接的语法。但是,当我尝试它时,我得到以下错误AttributeError:\uu退出\uuu。有什么好处?有什么想法吗?这里有许多类似的问题,尽管找不到令人满意的解决方案。以下是我迄今为止所做的尝试: 以下操作失败: import shelve with shelve.open('spam.db') as db: db['key'] = 'value' print(db['k

我正在尝试使用Python3.3。建议与搁置一起使用。将“spam.db”打开为db:。。。确保我们关闭连接的语法。但是,当我尝试它时,我得到以下错误AttributeError:\uu退出\uuu。有什么好处?有什么想法吗?这里有许多类似的问题,尽管找不到令人满意的解决方案。以下是我迄今为止所做的尝试:

以下操作失败:

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]
以及预期的产出:

value
[Finished in 0.1s]
打印搁置模块路径

import shelve
print(shelve)
地点:

<module 'shelve' from 'C:\\Python33\\lib\\shelve.py'>
[Finished in 0.1s]
在Python 3.3中,shelve.open不是上下文管理器,不能在with语句中使用。with语句预期会有;您看到的错误是因为没有这样的方法

您可以使用以下命令在上下文管理器中包装shelve.open结果:

from contextlib import closing

with closing(shelve.open('spam.db')) as db:
或者,升级到Python 3.4,其中所需的上下文管理器方法被添加到shelve.open的返回值中。从:

在版本3.4中更改:添加了上下文管理器支持

在Python 3.3中,shelve.open不是上下文管理器,不能在with语句中使用。with语句预期会有;您看到的错误是因为没有这样的方法

您可以使用以下命令在上下文管理器中包装shelve.open结果:

from contextlib import closing

with closing(shelve.open('spam.db')) as db:
或者,升级到Python 3.4,其中所需的上下文管理器方法被添加到shelve.open的返回值中。从:

在版本3.4中更改:添加了上下文管理器支持

Shelf不是Python 3.3中的上下文管理器;此功能在3.4中引入。如果需要支持3.3,则需要在finally块中使用contextlib.closing或显式closing。我建议使用contextlib.closing

Shelf不是Python 3.3中的上下文管理器;此功能在3.4中引入。如果需要支持3.3,则需要在finally块中使用contextlib.closing或显式closing。我建议使用contextlib.closing


shelve.open未返回上下文管理器。并修复:shelve.open未返回上下文管理器。费克斯:非常感谢!我正在阅读Python3 no'point'something文档,它似乎使用了最新的文档,即3.4,因此当它建议使用'with'时,我感到困惑。我想我只是升级一下。没有和3.3结婚。非常感谢!我正在阅读Python3 no'point'something文档,它似乎使用了最新的文档,即3.4,因此当它建议使用'with'时,我感到困惑。我想我只是升级一下。没有和3.3结婚。谢谢。你和Martijn Pieters同时提交。我会给他答案,但这实际上是武断的,因为你们两人的贡献是一样的。对不起,谢谢。你和Martijn Pieters同时提交。我会给他答案,但这实际上是武断的,因为你们两人的贡献是一样的。很抱歉。
import contextlib

with contextlib.closing(shelve.open('spam.db')) as db:
    do_whatever_with(db)