python中的Shelve模块不工作:“无法确定db type”

2024-06-18 05:40:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用Python编写一个简单的密码存储程序,它看起来非常简单,所以我想知道我是不是用错了shelve。

我有主.py文件:

import shelve

passwords = shelve.open('./passwords_dict.py')

choice = raw_input("Add password (a) or choose site (c)?")

if choice[0] == 'a':
    site_key = raw_input("Add for which site? ").lower()
    userpass = raw_input("Add any info such as username, email, or passwords: ")

    passwords[site_key] = userpass

else:
    site = raw_input("Which site? ").lower()
    if site in passwords:
        print "Info for " + site + ": " + passwords[site]
    else:
        print site, "doesn't seem to exist!"

print "Done!"

passwords.close()

另一个文件passwords_dict.py只是一个空字典。

但是当我试图运行程序时,我得到了一个错误:

Traceback (most recent call last):
File "passwords.py", line 3, in <module>
passwords = shelve.open('passwords_dict.py')
File "/usr/lib/python2.7/shelve.py", line 239, in open
return DbfilenameShelf(filename, flag, protocol, writeback)
File "/usr/lib/python2.7/shelve.py", line 223, in __init__
Shelf.__init__(self, anydbm.open(filename, flag), protocol, writeback)
File "/usr/lib/python2.7/anydbm.py", line 82, in open
raise error, "db type could not be determined"
anydbm.error: db type could not be determined

当我尝试改用anydbm时,会出现以下错误:

Traceback (most recent call last):
File "passwords.py", line 3, in <module>
passwords = anydbm.open('passwords_dict.py')
File "/usr/lib/python2.7/anydbm.py", line 82, in open
raise error, "db type could not be determined"
anydbm.error: db type could not be determined

当我尝试使用dbm时,会出现以下错误:

Traceback (most recent call last):
File "passwords.py", line 3, in <module>
passwords = dbm.open('./passwords_dict.py')
dbm.error: (2, 'No such file or directory')

我做错什么了?有没有另一种方法来存储字典,并且仍然能够使用用户输入来提取密钥(而不是整个字典,我想pickle就是这样做的)?


Tags: inpyinputrawlibusrlinesite
3条回答

任何数据库https://bugs.python.org/issue13007都有一个错误,无法对gdbm文件使用正确的标识。

因此,如果您试图用shelve打开一个有效的gdbm文件并正在处理该错误,请使用以下命令:

    mod = __import__("gdbm")
    file = shelve.Shelf(mod.open(filename, flag))

关于这个问题的更多信息:shelve db type could not be determined, whichdb is not recognizing gdb

我也经历过这个问题。它似乎与shelve.openfilename参数的未记录条件有关。它目前非常不妥协(例如,shelve.open("/tmp/tmphTTQLda")工作,而shelve.open("/tmp/tmphTTQLd")不工作)。变量文件名的失败和成功是很难预测的。我要求在http://bugs.python.org/issue23174以文档增强的形式进行解释。

在我的例子中,在shelve之外打开一个持久dict并将其传递给shelve.Shelveworks,例如code

a = dumbdbm.open(tempfile.mkstemp()[1])
b = shelve.Shelf(dict=a)

b做你用shelve.open返回值做的事情。

我想你误解了架子模块的工作原理。它打开一个数据库文件。当您尝试打开包含Python脚本的现有文件时,它会尝试检测该文件包含的数据库类型(因为shelve支持多个后端数据库)。

我想你想要这样的东西:

import os
import shelve

curdir = os.path.dirname(__file__)
passwords = shelve.open(os.path.join(curdir, 'password_db'))

这将在脚本所在的目录中创建一个名为password_db.<db>的新文件,其中<db>是特定于实现的数据库文件扩展名。

相关问题 更多 >