如果我尝试打开刚刚由 shelve 创建的文件,为什么 shelve 会引发错误?
import shelve
info_file_name = "/Users/bacon/myproject/temp/test.info"
info_file = shelve.open(info_file_name)
info_file['ok'] = 'wass'
info_file.close()
info_file = shelve.open(info_file_name) # raise exception db type could not be determined..
info_file.close()
我正在运行 python 2.5 以防相关
产生的精确误差是:
db type could not be determined
它的提出者是anydbm.py
open
method.
我知道它正在使用 gdbm。我检查了whichdb.py文件,它尝试用这个来识别gdbm文件
# Read the start of the file -- the magic number
s16 = f.read(16)
s = s16[0:4]
# Convert to 4-byte int in native byte order -- return "" if impossible
(magic,) = struct.unpack("=l", s)
# Check for GNU dbm
if magic == 0x13579ace:
return "gdbm"
但我文件中的“神奇”数字是324508367
(0x13579acf
) (仅最后一位数字发生变化!)
我尝试使用另一种语言(ruby)打开该文件,并且能够毫无问题地打开它,所以这似乎是whichdb.py中试图识别正确的dbm的错误
正如问题中所解释的,此错误是由于 whichdb 中的错误无法识别某些最新的 gdb 文件造成的,更多信息位于此错误报告中:https://bugs.python.org/issue13007 https://bugs.python.org/issue13007
最好的解决方案是强制数据库定义一个使用 gdbm 加载架子的方法,而不是尝试猜测 dbm。
def gdbm_shelve(filename, flag="c"):
mod = __import__("gdbm")
return shelve.Shelf(mod.open(filename, flag))
然后用它代替shelve.open
:
info_file = gdbm_shelve(info_file_name)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)