blob: ed05921e6ffc5c04f9305968766e6fcd1fb9fd5a [file] [log] [blame]
Georg Brandl0a7ac7d2008-05-26 10:29:35 +00001:mod:`dbm` --- Interfaces to Unix "databases"
2=============================================
Georg Brandl116aa622007-08-15 14:28:22 +00003
4.. module:: dbm
Georg Brandl0a7ac7d2008-05-26 10:29:35 +00005 :synopsis: Interfaces to various Unix "database" formats.
6
7:mod:`dbm` is a generic interface to variants of the DBM database ---
Benjamin Peterson905aa662008-09-08 21:35:37 +00008 :mod:`dbm.gnu` or :mod:`dbm.ndbm`. If none of these modules is installed, the
9 slow-but-simple implementation in module :mod:`dbm.dumb` will be used. There
10 is a `third party interface <http://www.jcea.es/programacion/pybsddb.htm>`_ to
11 the Oracle Berkely DB.
Georg Brandl0a7ac7d2008-05-26 10:29:35 +000012
13
14.. exception:: error
15
16 A tuple containing the exceptions that can be raised by each of the supported
17 modules, with a unique exception also named :exc:`dbm.error` as the first
18 item --- the latter is used when :exc:`dbm.error` is raised.
19
20
21.. function:: whichdb(filename)
22
23 This functionattempts to guess which of the several simple database modules
24 available --- :mod:`dbm.bsd`, :mod:`dbm.gnu`, :mod:`dbm.ndbm` or
25 :mod:`dbm.dumb` --- should be used to open a given file.
26
27 Returns one of the following values: ``None`` if the file can't be opened
28 because it's unreadable or doesn't exist; the empty string (``''``) if the
29 file's format can't be guessed; or a string containing the required module
30 name, such as ``'dbm.ndbm'`` or ``'dbm.gnu'``.
31
32
33.. function:: open(filename[, flag[, mode]])
34
35 Open the database file *filename* and return a corresponding object.
36
37 If the database file already exists, the :func:`whichdb` function is used to
38 determine its type and the appropriate module is used; if it does not exist,
39 the first module listed above that can be imported is used.
40
41 The optional *flag* argument can be ``'r'`` to open an existing database for
42 reading only, ``'w'`` to open an existing database for reading and writing,
43 ``'c'`` to create the database if it doesn't exist, or ``'n'``, which will
44 always create a new empty database. If not specified, the default value is
45 ``'r'``.
46
47 The optional *mode* argument is the Unix mode of the file, used only when the
48 database has to be created. It defaults to octal ``0o666`` (and will be
49 modified by the prevailing umask).
50
51
52The object returned by :func:`open` supports most of the same functionality as
53dictionaries; keys and their corresponding values can be stored, retrieved, and
54deleted, and the :keyword:`in` operator and the :meth:`keys` method are
55available. Keys and values must always be strings.
56
57The following example records some hostnames and a corresponding title, and
58then prints out the contents of the database::
59
60 import dbm
61
62 # Open database, creating it if necessary.
63 db = dbm.open('cache', 'c')
64
65 # Record some values
66 db['www.python.org'] = 'Python Website'
67 db['www.cnn.com'] = 'Cable News Network'
68
69 # Loop through contents. Other dictionary methods
70 # such as .keys(), .values() also work.
71 for k, v in db.iteritems():
72 print(k, '\t', v)
73
74 # Storing a non-string key or value will raise an exception (most
75 # likely a TypeError).
76 db['www.yahoo.com'] = 4
77
78 # Close when done.
79 db.close()
80
81
82.. seealso::
83
84 Module :mod:`shelve`
85 Persistence module which stores non-string data.
86
87
88The individual submodules are described in the following sections.
89
90
Georg Brandl0a7ac7d2008-05-26 10:29:35 +000091:mod:`dbm.gnu` --- GNU's reinterpretation of dbm
92------------------------------------------------
93
94.. module:: dbm.gnu
95 :platform: Unix
96 :synopsis: GNU's reinterpretation of dbm.
97
98
99This module is quite similar to the :mod:`dbm` module, but uses the GNU library
100``gdbm`` instead to provide some additional functionality. Please note that the
101file formats created by ``gdbm`` and ``dbm`` are incompatible.
102
103The :mod:`dbm.gnu` module provides an interface to the GNU DBM library.
104``gdbm`` objects behave like mappings (dictionaries), except that keys and
105values are always strings. Printing a :mod:`dbm.gnu` object doesn't print the
106keys and values, and the :meth:`items` and :meth:`values` methods are not
107supported.
108
109.. exception:: error
110
111 Raised on ``gdbm``\ -specific errors, such as I/O errors. :exc:`KeyError` is
112 raised for general mapping errors like specifying an incorrect key.
113
114
115.. function:: open(filename, [flag, [mode]])
116
117 Open a ``gdbm`` database and return a :class:`gdbm` object. The *filename*
118 argument is the name of the database file.
119
120 The optional *flag* argument can be:
121
122 +---------+-------------------------------------------+
123 | Value | Meaning |
124 +=========+===========================================+
125 | ``'r'`` | Open existing database for reading only |
126 | | (default) |
127 +---------+-------------------------------------------+
128 | ``'w'`` | Open existing database for reading and |
129 | | writing |
130 +---------+-------------------------------------------+
131 | ``'c'`` | Open database for reading and writing, |
132 | | creating it if it doesn't exist |
133 +---------+-------------------------------------------+
134 | ``'n'`` | Always create a new, empty database, open |
135 | | for reading and writing |
136 +---------+-------------------------------------------+
137
138 The following additional characters may be appended to the flag to control
139 how the database is opened:
140
141 +---------+--------------------------------------------+
142 | Value | Meaning |
143 +=========+============================================+
144 | ``'f'`` | Open the database in fast mode. Writes |
145 | | to the database will not be synchronized. |
146 +---------+--------------------------------------------+
147 | ``'s'`` | Synchronized mode. This will cause changes |
148 | | to the database to be immediately written |
149 | | to the file. |
150 +---------+--------------------------------------------+
151 | ``'u'`` | Do not lock database. |
152 +---------+--------------------------------------------+
153
154 Not all flags are valid for all versions of ``gdbm``. The module constant
155 :const:`open_flags` is a string of supported flag characters. The exception
156 :exc:`error` is raised if an invalid flag is specified.
157
158 The optional *mode* argument is the Unix mode of the file, used only when the
Georg Brandlf4a41232008-05-26 17:55:52 +0000159 database has to be created. It defaults to octal ``0o666``.
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000160
161 In addition to the dictionary-like methods, ``gdbm`` objects have the
162 following methods:
163
164 .. method:: gdbm.firstkey()
165
166 It's possible to loop over every key in the database using this method and the
167 :meth:`nextkey` method. The traversal is ordered by ``gdbm``'s internal
168 hash values, and won't be sorted by the key values. This method returns
169 the starting key.
170
171 .. method:: gdbm.nextkey(key)
172
173 Returns the key that follows *key* in the traversal. The following code prints
174 every key in the database ``db``, without having to create a list in memory that
175 contains them all::
176
177 k = db.firstkey()
178 while k != None:
179 print(k)
180 k = db.nextkey(k)
181
182 .. method:: gdbm.reorganize()
183
184 If you have carried out a lot of deletions and would like to shrink the space
185 used by the ``gdbm`` file, this routine will reorganize the database. ``gdbm``
186 will not shorten the length of a database file except by using this
187 reorganization; otherwise, deleted file space will be kept and reused as new
188 (key, value) pairs are added.
189
190 .. method:: gdbm.sync()
191
192 When the database has been opened in fast mode, this method forces any
193 unwritten data to be written to the disk.
194
195
196:mod:`dbm.ndbm` --- Interface based on ndbm
197-------------------------------------------
198
199.. module:: dbm.ndbm
Georg Brandl116aa622007-08-15 14:28:22 +0000200 :platform: Unix
201 :synopsis: The standard "database" interface, based on ndbm.
202
203
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000204The :mod:`dbm.ndbm` module provides an interface to the Unix "(n)dbm" library.
205Dbm objects behave like mappings (dictionaries), except that keys and values are
Georg Brandl116aa622007-08-15 14:28:22 +0000206always strings. Printing a dbm object doesn't print the keys and values, and the
207:meth:`items` and :meth:`values` methods are not supported.
208
209This module can be used with the "classic" ndbm interface, the BSD DB
210compatibility interface, or the GNU GDBM compatibility interface. On Unix, the
211:program:`configure` script will attempt to locate the appropriate header file
212to simplify building this module.
213
Georg Brandl116aa622007-08-15 14:28:22 +0000214.. exception:: error
215
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000216 Raised on dbm-specific errors, such as I/O errors. :exc:`KeyError` is raised
217 for general mapping errors like specifying an incorrect key.
Georg Brandl116aa622007-08-15 14:28:22 +0000218
219
220.. data:: library
221
222 Name of the ``ndbm`` implementation library used.
223
224
225.. function:: open(filename[, flag[, mode]])
226
227 Open a dbm database and return a dbm object. The *filename* argument is the
228 name of the database file (without the :file:`.dir` or :file:`.pag` extensions;
229 note that the BSD DB implementation of the interface will append the extension
230 :file:`.db` and only create one file).
231
232 The optional *flag* argument must be one of these values:
233
234 +---------+-------------------------------------------+
235 | Value | Meaning |
236 +=========+===========================================+
237 | ``'r'`` | Open existing database for reading only |
238 | | (default) |
239 +---------+-------------------------------------------+
240 | ``'w'`` | Open existing database for reading and |
241 | | writing |
242 +---------+-------------------------------------------+
243 | ``'c'`` | Open database for reading and writing, |
244 | | creating it if it doesn't exist |
245 +---------+-------------------------------------------+
246 | ``'n'`` | Always create a new, empty database, open |
247 | | for reading and writing |
248 +---------+-------------------------------------------+
249
250 The optional *mode* argument is the Unix mode of the file, used only when the
Georg Brandlf4a41232008-05-26 17:55:52 +0000251 database has to be created. It defaults to octal ``0o666`` (and will be
Georg Brandl116aa622007-08-15 14:28:22 +0000252 modified by the prevailing umask).
253
254
Georg Brandl116aa622007-08-15 14:28:22 +0000255
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000256:mod:`dbm.dumb` --- Portable DBM implementation
257-----------------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000258
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000259.. module:: dbm.dumb
260 :synopsis: Portable implementation of the simple DBM interface.
Georg Brandl116aa622007-08-15 14:28:22 +0000261
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000262.. index:: single: databases
Georg Brandl116aa622007-08-15 14:28:22 +0000263
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000264.. note::
265
266 The :mod:`dbm.dumb` module is intended as a last resort fallback for the
267 :mod:`dbm` module when no more robust module is available. The :mod:`dbm.dumb`
268 module is not written for speed and is not nearly as heavily used as the other
269 database modules.
270
271The :mod:`dbm.dumb` module provides a persistent dictionary-like interface which
Benjamin Peterson9a46cab2008-09-08 02:49:30 +0000272is written entirely in Python. Unlike other modules such as :mod:`gdbm` no
273external library is required. As with other persistent mappings, the keys and
274values must always be strings.
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000275
276The module defines the following:
277
278
279.. exception:: error
280
281 Raised on dbm.dumb-specific errors, such as I/O errors. :exc:`KeyError` is
282 raised for general mapping errors like specifying an incorrect key.
283
284
285.. function:: open(filename[, flag[, mode]])
286
287 Open a dumbdbm database and return a dumbdbm object. The *filename* argument is
288 the basename of the database file (without any specific extensions). When a
289 dumbdbm database is created, files with :file:`.dat` and :file:`.dir` extensions
290 are created.
291
292 The optional *flag* argument is currently ignored; the database is always opened
293 for update, and will be created if it does not exist.
294
295 The optional *mode* argument is the Unix mode of the file, used only when the
296 database has to be created. It defaults to octal ``0o666`` (and will be modified
297 by the prevailing umask).
298
299 In addition to the methods provided by the :class:`collections.MutableMapping` class,
300 :class:`dumbdbm` objects provide the following method:
301
302 .. method:: dumbdbm.sync()
303
304 Synchronize the on-disk directory and data files. This method is called
305 by the :meth:`Shelve.sync` method.