1 """Guess which db package to use to open a db file."""
11 # just some sort of valid exception which might be raised in the
15 def whichdb(filename
):
16 """Guess which db package to use to open a db file.
20 - None if the database file can't be read;
21 - empty string if the file can be read but can't be recognized
22 - the module name (e.g. "dbm" or "gdbm") if recognized.
24 Importing the given module may still fail, and opening the
25 database using that module may still fail.
28 # Check for dbm first -- this has a .pag and a .dir file
30 f
= open(filename
+ os
.extsep
+ "pag", "rb")
32 f
= open(filename
+ os
.extsep
+ "dir", "rb")
36 # some dbm emulations based on Berkeley DB generate a .db file
37 # some do not, but they should be caught by the dbhash checks
39 f
= open(filename
+ os
.extsep
+ "db", "rb")
41 # guarantee we can actually open the file using dbm
42 # kind of overkill, but since we are dealing with emulations
43 # it seems like a prudent step
45 d
= dbm
.open(filename
)
48 except (IOError, _dbmerror
):
51 # Check for dumbdbm next -- this has a .dir and and a .dat file
53 f
= open(filename
+ os
.extsep
+ "dat", "rb")
55 f
= open(filename
+ os
.extsep
+ "dir", "rb")
57 if f
.read(1) in ["'", '"']:
64 # See if the file exists, return None if not
66 f
= open(filename
, "rb")
70 # Read the start of the file -- the magic number
75 # Return "" if not at least 4 bytes
79 # Convert to 4-byte int in native byte order -- return "" if impossible
81 (magic
,) = struct
.unpack("=l", s
)
86 if magic
== 0x13579ace:
90 if magic
in (0x00061561, 0x61150600):
93 # BSD hash v2 has a 12-byte NULL pad in front of the file type
95 (magic
,) = struct
.unpack("=l", s16
[-4:])
100 if magic
in (0x00061561, 0x61150600):