whichdb.py 1.33 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
"""Guess which db package to use to open a db file."""

import struct

def whichdb(filename):
    """Guess which db package to use to open a db file.

    Return values:

    - None if the database file can't be read;
    - empty string if the file can be read but can't be recognized
    - the module name (e.g. "dbm" or "gdbm") if recognized.

    Importing the given module may still fail, and opening the
    database using that module may still fail.
    """

    # Check for dbm first -- this has a .pag and a .dir file
    try:
20 21 22 23 24
        f = open(filename + ".pag", "rb")
        f.close()
        f = open(filename + ".dir", "rb")
        f.close()
        return "dbm"
25
    except IOError:
26
        pass
27 28 29

    # See if the file exists, return None if not
    try:
30
        f = open(filename, "rb")
31
    except IOError:
32
        return None
33 34 35 36 37 38 39

    # Read the first 4 bytes of the file -- the magic number
    s = f.read(4)
    f.close()

    # Return "" if not at least 4 bytes
    if len(s) != 4:
40
        return ""
41 42 43

    # Convert to 4-byte int in native byte order -- return "" if impossible
    try:
44
        (magic,) = struct.unpack("=l", s)
45
    except struct.error:
46
        return ""
47 48 49

    # Check for GNU dbm
    if magic == 0x13579ace:
50
        return "gdbm"
51 52 53

    # Check for BSD hash
    if magic == 0x061561:
54
        return "dbhash"
55 56 57

    # Unknown
    return ""