如何用Python读取Berkeley DB文件?

0 投票
2 回答
3225 浏览
提问于 2025-04-18 01:55

我该如何用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
    >>> 

... 我哪里做错了呢?

2 个回答

0

有几种方法可以打开Berkeley数据库文件。要查看有哪些可用的方法,你可以使用:

import bsddb3
print(dir(bsddb3))

要找出该用哪个方法打开你的文件,可以使用Linux的“file”命令,比如:

 file SomeFileName

关于如何打开Berkeley DB文件的详细说明,可以在《Python in a Nutshell》这本书中找到: https://www.oreilly.com/library/view/python-in-a/0596001886/re342.html

需要注意的是,Berkeley数据库在Python 2.7中是自动包含的,但在Python 3中就没有了。使用Python 3时,需要单独安装Berkeley DB。安装Berkeley DB的方法在Linux上取决于你使用的发行版。在SUSE上,我使用了:

zypper install python3-bsddb3
zypper install python3-bsddb3-devel
1

这里是与这个错误相关的代码,来自 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 模块(导入它并用它替代 anydbm),要么你需要安装其他库 dbhash gdbm, dbm 来打开这个文件。

撰写回答