dbm — Interfaces to Unix “databases”

Source code: Lib/dbm/__init__.py


dbm is a generic interface to variants of the DBM database — dbm.gnu or dbm.ndbm. 是DBM数据库变量dbm.gnudbm.ndbm的通用接口。If none of these modules is installed, the slow-but-simple implementation in module dbm.dumb will be used. 如果没有安装这些模块,将使用模块dbm.dumb中缓慢但简单的实现。There is a third party interface to the Oracle Berkeley DB.Oracle Berkeley DB有第三方接口

exceptiondbm.error

A tuple containing the exceptions that can be raised by each of the supported modules, with a unique exception also named dbm.error as the first item — the latter is used when dbm.error is raised.一个元组,包含每个受支持的模块都可以引发的异常,第一项是一个唯一的异常,也称为dbm.error,当引发dbmerrror时使用后者。

dbm.whichdb(filename)

This function attempts to guess which of the several simple database modules available — dbm.gnu, dbm.ndbm or dbm.dumb — should be used to open a given file.此函数尝试猜测可用的几个简单数据库模块中的哪一个(dbm.gnudbm.ndbmdbm.dumb)应该用于打开给定的文件。

Returns one of the following values: None if the file can’t be opened because it’s unreadable or doesn’t exist; the empty string ('') if the file’s format can’t be guessed; or a string containing the required module name, such as 'dbm.ndbm' or 'dbm.gnu'.返回以下值之一:如果文件不可读或不存在而无法打开,则返回None;如果无法猜测文件的格式,则为空字符串('');或包含所需模块名称的字符串,例如'dbm.ndbm''dbm.gnu'

dbm.open(file, flag='r', mode=438)

Open the database file file and return a corresponding object.打开数据库文件file并返回相应的对象。

If the database file already exists, the whichdb() function is used to determine its type and the appropriate module is used; if it does not exist, the first module listed above that can be imported is used.如果数据库文件已经存在,则使用whichdb()函数确定其类型,并使用适当的模块;如果不存在,则使用上面列出的可以导入的第一个模块。

The optional flag argument can be:可选flag参数可以是:

Value

Meaning含义

'r'

Open existing database for reading only (default)以只读方式打开现有数据库(默认)

'w'

Open existing database for reading and writing打开现有数据库进行读写

'c'

Open database for reading and writing, creating it if it doesn’t exist打开数据库进行读写,如果不存在则创建数据库

'n'

Always create a new, empty database, open for reading and writing始终创建一个新的空数据库,打开以供读取和写入

The optional mode argument is the Unix mode of the file, used only when the database has to be created. 可选mode参数是文件的Unix模式,仅在必须创建数据库时使用。It defaults to octal 0o666 (and will be modified by the prevailing umask).它默认为八进制0o666(并将被流行的umask修改)。

The object returned by open() supports the same basic functionality as dictionaries; keys and their corresponding values can be stored, retrieved, and deleted, and the in operator and the keys() method are available, as well as get() and setdefault().open()返回的对象支持与字典相同的基本功能;可以存储、检索和删除键及其对应的值,并且可以使用in运算符和keys()方法以及get()setdefault()

Changed in version 3.2:版本3.2中更改: get() and setdefault() are now available in all database modules.现在在所有数据库模块中都可用。

Changed in version 3.8:版本3.8中更改: Deleting a key from a read-only database raises database module specific error instead of KeyError.从只读数据库中删除密钥会引发数据库模块特定的错误,而不是KeyError

Key and values are always stored as bytes. 键和值始终存储为字节。This means that when strings are used they are implicitly converted to the default encoding before being stored.这意味着当使用字符串时,它们在存储之前会隐式转换为默认编码。

These objects also support being used in a with statement, which will automatically close them when done.这些对象还支持在with语句中使用,完成后会自动关闭它们。

Changed in version 3.4:版本3.4中更改: Added native support for the context management protocol to the objects returned by open().open()返回的对象添加了对上下文管理协议的本机支持。

The following example records some hostnames and a corresponding title, and then prints out the contents of the database:以下示例记录了一些主机名和相应的标题,然后打印出数据库的内容:

import dbm
# Open database, creating it if necessary.
with dbm.open('cache', 'c') as db:

# Record some values
db[b'hello'] = b'there'
db['www.python.org'] = 'Python Website'
db['www.cnn.com'] = 'Cable News Network'

# Note that the keys are considered bytes now.
assert db[b'www.python.org'] == b'Python Website'
# Notice how the value is now in bytes.
assert db['www.cnn.com'] == b'Cable News Network'

# Often-used methods of the dict interface work too.
print(db.get('python.org', b'not present'))

# Storing a non-string key or value will raise an exception (most
# likely a TypeError).
db['www.yahoo.com'] = 4

# db is automatically closed when leaving the with statement.

See also

Module shelve

Persistence module which stores non-string data.存储非字符串数据的持久性模块。

The individual submodules are described in the following sections.各个子模块在以下章节中进行了描述。

dbm.gnuGNU’s reinterpretation of dbmGNU对dbm的重新解释

Source code: Lib/dbm/gnu.py


This module is quite similar to the dbm module, but uses the GNU library gdbm instead to provide some additional functionality. 该模块与dbm模块非常相似,但使用GNU库gdbm来提供一些附加功能。Please note that the file formats created by dbm.gnu and dbm.ndbm are incompatible.请注意,dbm.gnudbm.ndbm创建的文件格式不兼容。

The dbm.gnu module provides an interface to the GNU DBM library. dbm.gnu模块提供GNU DBM库的接口。dbm.gnu.gdbm objects behave like mappings (dictionaries), except that keys and values are always converted to bytes before storing. 对象的行为类似于映射(字典),只是键和值在存储之前总是转换为字节。Printing a gdbm object doesn’t print the keys and values, and the items() and values() methods are not supported.打印gdbm对象不会打印键和值,不支持items()values()方法。

exceptiondbm.gnu.error

Raised on dbm.gnu-specific errors, such as I/O errors. dbm.gnu特定错误(如I/O错误)上引发。KeyError is raised for general mapping errors like specifying an incorrect key.对于常规映射错误(如指定错误的键),会引发KeyError

dbm.gnu.open(filename[, flag[, mode]])

Open a gdbm database and return a gdbm object. 打开gdbm数据库并返回gdbm对象。The filename argument is the name of the database file.filename参数是数据库文件的名称。

The optional flag argument can be:可选flag参数可以是:

Value

Meaning含义

'r'

Open existing database for reading only (default)以只读方式打开现有数据库(默认)

'w'

Open existing database for reading and writing打开现有数据库进行读写

'c'

Open database for reading and writing, creating it if it doesn’t exist打开数据库进行读写,如果不存在则创建数据库

'n'

Always create a new, empty database, open for reading and writing始终创建一个新的空数据库,打开以供读取和写入

The following additional characters may be appended to the flag to control how the database is opened:以下附加字符可能会附加到标志中,以控制数据库的打开方式:

Value

Meaning

'f'

Open the database in fast mode. 以快速模式打开数据库。Writes to the database will not be synchronized.不会同步对数据库的写入。

's'

Synchronized mode. 同步模式。This will cause changes to the database to be immediately written to the file.这将导致对数据库的更改立即写入文件。

'u'

Do not lock database.不要锁定数据库。

Not all flags are valid for all versions of gdbm. 并非所有标志对所有版本的gdbm都有效。The module constant open_flags is a string of supported flag characters. 模块常量open_flags是一个支持的标志字符字符串。The exception error is raised if an invalid flag is specified.如果指定的标志无效,将引发异常error

The optional mode argument is the Unix mode of the file, used only when the database has to be created. 可选mode参数是文件的Unix模式,仅在必须创建数据库时使用。It defaults to octal 0o666.默认为八进制0o666

In addition to the dictionary-like methods, gdbm objects have the following methods:除了类似字典的方法外,gdbm对象还有以下方法:

gdbm.firstkey()

It’s possible to loop over every key in the database using this method and the nextkey() method. 可以使用此方法和nextkey()方法循环数据库中的每个键。The traversal is ordered by gdbm’s internal hash values, and won’t be sorted by the key values. 遍历是按gdbm的内部哈希值排序的,不会按键值排序。This method returns the starting key.此方法返回起始键。

gdbm.nextkey(key)

Returns the key that follows key in the traversal. 返回遍历中key之后的键。The following code prints every key in the database db, without having to create a list in memory that contains them all:以下代码打印数据库db中的每个键,而不必在内存中创建包含所有键的列表:

k = db.firstkey()
while k is not None:
print(k)
k = db.nextkey(k)
gdbm.reorganize()

If you have carried out a lot of deletions and would like to shrink the space used by the gdbm file, this routine will reorganize the database. 如果您执行了大量删除操作,并且希望缩小gdbm文件使用的空间,那么这个例程将重新组织数据库。gdbm objects will not shorten the length of a database file except by using this reorganization; otherwise, deleted file space will be kept and reused as new (key, value) pairs are added.对象不会缩短数据库文件的长度,除非使用这种重组;否则,当添加新的(键、值)对时,将保留并重用删除的文件空间。

gdbm.sync()

When the database has been opened in fast mode, this method forces any unwritten data to be written to the disk.当数据库以快速模式打开时,此方法强制将任何未写入的数据写入磁盘。

gdbm.close()

Close the gdbm database.关闭gdbm数据库。

dbm.ndbmInterface based on ndbm基于ndbm的接口

Source code: Lib/dbm/ndbm.py


The dbm.ndbm module provides an interface to the Unix “(n)dbm” library. dbm.ndbm模块提供到Unix“(n)dbm”库的接口。Dbm objects behave like mappings (dictionaries), except that keys and values are always stored as bytes. Dbm对象的行为类似于映射(字典),只是键和值总是存储为字节。Printing a dbm object doesn’t print the keys and values, and the items() and values() methods are not supported.打印dbm对象不会打印键和值,不支持items()values()方法。

This module can be used with the “classic” ndbm interface or the GNU GDBM compatibility interface. 此模块可以与“经典”ndbm接口或GNU GDBM兼容接口一起使用。On Unix, the configure script will attempt to locate the appropriate header file to simplify building this module.在Unix上,configure脚本将尝试找到适当的头文件,以简化此模块的构建。

exceptiondbm.ndbm.error

Raised on dbm.ndbm-specific errors, such as I/O errors. dbm.ndbm特定错误(如I/O错误)上引发。KeyError is raised for general mapping errors like specifying an incorrect key.对于常规映射错误(如指定错误的键),会引发KeyError

dbm.ndbm.library

Name of the ndbm implementation library used.使用的ndbm实现库的名称。

dbm.ndbm.open(filename[, flag[, mode]])

Open a dbm database and return a ndbm object. 打开dbm数据库并返回ndbm对象。The filename argument is the name of the database file (without the .dir or .pag extensions).filename参数是数据库文件的名称(不带.dir.pag扩展名)。

The optional flag argument must be one of these values:可选flag参数必须是以下值之一:

Value

Meaning含义

'r'

Open existing database for reading only (default)以只读方式打开现有数据库(默认)

'w'

Open existing database for reading and writing打开现有数据库进行读写

'c'

Open database for reading and writing, creating it if it doesn’t exist打开数据库进行读写,如果不存在则创建数据库

'n'

Always create a new, empty database, open for reading and writing始终创建一个新的空数据库,打开以供读取和写入

The optional mode argument is the Unix mode of the file, used only when the database has to be created. 可选mode参数是文件的Unix模式,仅在必须创建数据库时使用。It defaults to octal 0o666 (and will be modified by the prevailing umask).它默认为八进制0o666(并将被流行的umask修改)。

In addition to the dictionary-like methods, ndbm objects provide the following method:除了类似字典的方法外,ndbm对象还提供以下方法:

ndbm.close()

Close the ndbm database.关闭ndbm数据库。

dbm.dumbPortable DBM implementation可移植DBM实现

Source code: Lib/dbm/dumb.py

Note

The dbm.dumb module is intended as a last resort fallback for the dbm module when a more robust module is not available. 当没有更健壮的模块可用时,dbm.dumb模块是dbm模块的最后一个备用模块。The dbm.dumb module is not written for speed and is not nearly as heavily used as the other database modules.dbm.dumb模块不是为了速度而编写的,使用量也不如其他数据库模块大。


The dbm.dumb module provides a persistent dictionary-like interface which is written entirely in Python. dbm.dumb模块提供了一个完全用Python编写的类字典的持久接口。Unlike other modules such as dbm.gnu no external library is required. 与其他模块(如dbm.gnu)不同,不需要外部库。As with other persistent mappings, the keys and values are always stored as bytes.与其他持久映射一样,键和值始终存储为字节。

The module defines the following:该模块定义了以下内容:

exceptiondbm.dumb.error

Raised on dbm.dumb-specific errors, such as I/O errors. dbm.dumb特定错误(如I/O错误)上引发。KeyError is raised for general mapping errors like specifying an incorrect key.对于常规映射错误(如指定错误的键),会引发KeyError

dbm.dumb.open(filename[, flag[, mode]])

Open a dumbdbm database and return a dumbdbm object. 打开一个dumbdbm数据库并返回一个dumbdbm对象。The filename argument is the basename of the database file (without any specific extensions). filename参数是数据库文件的基本名称(没有任何特定扩展名)。When a dumbdbm database is created, files with .dat and .dir extensions are created.创建dumbdbm数据库时,将创建扩展名为.dat.dir的文件。

The optional flag argument can be:

Value

Meaning含义

'r'

Open existing database for reading only (default)以只读方式打开现有数据库(默认)

'w'

Open existing database for reading and writing打开现有数据库进行读写

'c'

Open database for reading and writing, creating it if it doesn’t exist打开数据库进行读写,如果不存在则创建数据库

'n'

Always create a new, empty database, open for reading and writing始终创建一个新的空数据库,打开以供读取和写入

The optional mode argument is the Unix mode of the file, used only when the database has to be created. 可选mode参数是文件的Unix模式,仅在必须创建数据库时使用。It defaults to octal 0o666 (and will be modified by the prevailing umask).它默认为八进制0o666(并将被流行的umask修改)。

Warning警告

It is possible to crash the Python interpreter when loading a database with a sufficiently large/complex entry due to stack depth limitations in Python’s AST compiler.由于Python的AST编译器中的堆栈深度限制,当加载具有足够大/复杂条目的数据库时,可能会导致Python解释器崩溃。

Changed in version 3.5:版本3.5中更改: open() always creates a new database when the flag has the value 'n'.当标志的值为'n'时,总是创建一个新数据库。

Changed in version 3.8:版本3.8中更改: A database opened with flags 'r' is now read-only. 用标志'r'打开的数据库现在是只读的。Opening with flags 'r' and 'w' no longer creates a database if it does not exist.如果数据库不存在,则使用标志'r''w'打开时将不再创建数据库。

In addition to the methods provided by the collections.abc.MutableMapping class, dumbdbm objects provide the following methods:除了collections.abc.MutableMapping类提供的方法外,dumbdbm对象还提供以下方法:

dumbdbm.sync()

Synchronize the on-disk directory and data files. 同步磁盘目录和数据文件。This method is called by the Shelve.sync() method.此方法由Shelve.sync()方法调用。

dumbdbm.close()

Close the dumbdbm database.关闭dumbdbm数据库。