Skip to main content
 首页 » 编程设计

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

2025年05月04日13birdshome

我正在尝试使用 shelve使用 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_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] 

请您参考如下方法:

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

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

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

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

Changed in version 3.4: Added context manager support.