Shelve problem in 1.5.2
Skip Montanaro
skip at mojam.com
Fri Oct 29 10:45:11 EDT 1999
Nick> I have just upgraded from 1.5.1 to 1.5.2 on a Linux/RedHat(now
Nick> 6.1) system and my shelve module is behaving strangely. It fails
Nick> to open old files and if I open and close a new file it is happy
Nick> but as soon as I try to open the newly created file it fails
Nick> also...
Nick,
Try the attached version of whichdb.py to see if it cures your ills.
Skip Montanaro | http://www.mojam.com/
skip at mojam.com | http://www.musi-cal.com/
847-971-7098 | Python: Programming the way Guido indented...
--[[application/octet-stream
Content-Disposition: attachment; filename="whichdb.py"][quoted-printable]]
"""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:
f =3D open(filename + ".pag", "rb")
f.close()
f =3D open(filename + ".dir", "rb")
f.close()
return "dbm"
except IOError:
pass
# See if the file exists, return None if not
try:
f =3D open(filename, "rb")
except IOError:
return None
# Read the start of the file -- the magic number
s16 =3D f.read(16)
f.close()
s =3D s16[0:4]
# Return "" if not at least 4 bytes
if len(s) !=3D 4:
return ""
# Convert to 4-byte int in native byte order -- return "" if impossib=
le
try:
(magic,) =3D struct.unpack("=3Dl", s)
except struct.error:
return ""
# Check for GNU dbm
if magic =3D=3D 0x13579ace:
return "gdbm"
# Check for BSD hash
if magic in (0x00061561, 0x61150600):
return "dbhash"
# BSD hash v2 has a 12-byte NULL pad in front of the file type
try:
(magic,) =3D struct.unpack("=3Dl", s16[-4:])
except struct.error:
return ""
# Check for BSD hash
if magic in (0x00061561, 0x61150600):
return "dbhash"
# Unknown
return ""
More information about the Python-list
mailing list