如何使用 Python 读取 Berkeley DB 文件?
我有这个文件...
[root@dhcp-idev1 ndb]# file dhcp.ndb
dhcp.ndb: Berkeley DB (Btree, version 9, native byte-order)
...所以我想我可以做到这一点...
[root@dhcp-idev1 ndb]# python2.3
Python 2.3.4 (#1, Jul 16 2009, 07:01:37)
[GCC 3.4.6 20060404 (Red Hat 3.4.6-11)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import anydbm
>>> anydbm.open( './dhcp.ndb' )
...但我收到此错误消息...
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/usr/lib/python2.3/anydbm.py", line 80, in open
raise error, "db type could not be determined"
anydbm.error: db type could not be determined
>>>
...我做错了什么?
这里是与此错误相关的代码来自
anydbm.py
from whichdb import whichdb
result=whichdb(file)
if result is None:
# db doesn't exist
if 'c' in flag or 'n' in flag:
# file doesn't exist and the new
# flag was used so use default type
mod = _defaultmod
else:
raise error, "need 'c' or 'n' flag to open new db"
elif result == "":
# db type cannot be determined
raise error, "db type could not be determined"
如果
whichdb
可以打开文件但无法确定要使用的库,则返回空字符串。
所以问题是为什么它无法确定库。可能未安装打开此数据库文件所需的库。
anydbm is a generic interface to variants of the DBM database — dbhash (requires
bsddb), gdbm, or dbm. If none of these modules is installed, the slow-but-simple
implementation in module dumbdbm will be used.
因此,要么您缺少
dumbdbm
模块(导入它并使用它而不是任何dbm),要么您需要安装其他库 dbhash gdbm, dbm
才能打开该文件。
打开 Berkeley 数据库文件的方法有多种。要了解可用的方法,您可以使用:
import bsddb3
print(dir(bsddb3))
要了解对文件使用哪种方法,您可以使用 Linux“file”命令,例如:
文件某些文件名
《Python in a Nutshell》一书对如何打开 Berkeley DB 文件有清晰的解释: https://www.oreilly.com/library/view/python-in-a/0596001886/re342.html
需要注意的是,Berkeley 数据库自动包含在 Python 2.7 中,但不包含在 Python 3 中。使用 Python 3 时,必须单独安装 Berkeley DB。在 Linux 上安装 Berkeley DB 的方法取决于发行版。在 SUSE 上我使用:
zypper install python3-bsddb3
zypper install python3-bsddb3-devel