Shelve 在 Python 3.3 中为 hello world 示例提供了 AttributeError 使用 "with shelve.open" 语法,但并非没有它



我正在尝试使用Python 3.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_scriptnf_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]

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

您可以使用contextlib.closing()shelve.open()结果包装在上下文管理器中:

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

或者,升级到Python 3.4,所需的上下文管理器方法被添加到shelve.open()的返回值中。shelve.Shelve文档:

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

Shelf在Python 3.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)

最新更新