在10.5.8上通过Macports安装的Python 3.1 - shelve错误(是bug吗?)
我在用macports运行python 3.1.4,想要使用shelve模块。在另一台开发机器上(操作系统不同等)我可以顺利使用这个模块,所以我不太确定自己哪里出错了……
如果你有什么想法或建议,我会非常感激!
这是我遇到的错误:“dbm.error: 无法确定数据库类型”。(我搜索了这个错误信息,但没有找到相关资料——我甚至尝试强制设置protocol=2,看看是否有帮助,但没有效果)
下面是我的交互式会话:
Python 3.1.4 (default, Oct 7 2011, 15:58:53)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
>>> import shelve
>>> a = [1, 2, 3]
>>> locker = shelve.open('myshelf',protocol=2)
>>> locker['a'] = a
>>> locker.close()
>>> exit()
Python 3.1.4 (default, Oct 7 2011, 15:58:53)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
>>> import shelve
>>> locker = shelve.open('myshelf',protocol=2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/shelve.py", line 231, in open
return DbfilenameShelf(filename, flag, protocol, writeback)
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/shelve.py", line 215, in __init__
Shelf.__init__(self, dbm.open(filename, flag), protocol, writeback)
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/dbm/__init__.py", line 84, in open
raise error[0]("db type could not be determined")
dbm.error: db type could not be determined
2 个回答
可以使用 MacPorts 或 Homebrew 来安装 ndbm。然后用这个工具来创建数据库。等到你之后打开这个文件时,shelve 会自动调用 dbm.whichdb,这样就能成功识别这个文件了。
这看起来像是MacPorts的一个问题,或者是Python 3的一个bug。对我来说,你提供的例子在当前的MacPorts Python 2.7.2上可以正常工作,但在同样的MacPorts Python 3.2.2上就像你说的那样失败了。MacPorts会自动为Python 3的版本构建并包含gdbm
作为数据库管理工具;而对于Python 2,它同时包含了Berkeley的DB4.6
和gdbm
。看起来MacPorts 2.7.2使用的是db46,所以可以正常工作,但3.2.2在使用gdbm
时就失败了;可以推测MacPorts 3.1的情况也差不多。这个问题需要进一步调查。
更新:如果你使用的是最新的MacPorts安装,这很可能就是在http://bugs.python.org/issue13007上报告的问题。看起来有一个修复是为了支持最新的gdbm 1.9
及以后的版本 - 当前的MacPorts版本是1.9.1。这个修复是在Python 3.2.2发布后应用的(它会在3.2.3中出现);MacPorts的团队应该把这个修复应用到他们的Python版本中。