我试图在Python中创建一个简单的密码存储程序,它看起来很简单,所以我想知道我是否使用搁置错误.
我有主.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, inpasswords = 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, inpasswords = 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, inpasswords = dbm.open('./passwords_dict.py') dbm.error: (2, 'No such file or directory')
我究竟做错了什么?是否存在另一种存储字典的方法,并且仍然能够使用用户输入(而不是整个字典,我认为这是pickle所做的)提取密钥?
我认为你误解了搁架模块是如何工作的.它会打开一个数据库文件.当您尝试打开包含Python脚本的现有文件时,它会尝试检测该文件包含的数据库类型(因为shelve支持多个后端数据库).
我认为你需要这样的东西:
import os import shelve curdir = os.path.dirname(__file__) passwords = shelve.open(os.path.join(curdir, 'password_db'))
这将在与脚本相同的目录中创建一个新文件,password_db.
其中
是特定于实现的数据库文件扩展名.