python - KeyError and AtrributeError when trying to retrieve a shelved class - Python 3.6
问题描述
When serializing a class in one program(with shelve), I cannot retrieve it without getting the follow error:
File "\Python36_64\lib\shelve.py", line 111, in __getitem__
value = self.cache[key]
KeyError: 'foo'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "program.py", line 12, in <module>
bar = db['foo']
File "\Python36_64\lib\shelve.py", line 114, in __getitem__
value = Unpickler(f).load()
AttributeError: Can't get attribute 'bar' on <module '__main__' (built-in)>
This is my code initializing the shelf. It compiled:
import shelve
class bar:
x = {}
db = shelve.open('file.dat')
db['foo'] = bar
I've been trying to retrieve class bar in another program with the following code. This has not compiled properly.:
import shelve
db = shelve.open('file.dat')
bar = db['foo']
解决方案
你不能像这样腌制和解开它们来存储类。当pickle
需要pickle一个类时,它只记录类的模块和名称,而不是内容。只有在相同模块定义了相同类的环境中才能取消腌制。
推荐阅读
- mysql - 通过未在 mysql 中获得预期结果进行分组
- python - 如何使用 AWS Lambda 从 mysql 数据库返回大量列?
- dns - 选中“仅将此连接用于其网络上的资源”时,openvpn push DNS 失败
- excel - Excel VBA 阻止功能区
- bash - awk 或其他命令如何获取字符串 curl 结果的变量值?
- python - 为什么 len 不返回正确的值?
- go - 获取 cloud.google.com/go/datastore 会为 golang.org/x/lint 提供格式错误的记录数据
- java - 运行 Selenium 基本程序时启动 GC
- xml - VB6/VBA:如何使用 BOM 以 UTF-8 编写 xml 文件
- pyspark - Pyspark 错误将 StructType 传递给 Schema