I am writing a command line dbm editor and have ran into a small issue. If I try to run certain commands (ie add, remove, display) when I do not have a file open, I get the following error:
Traceback (most recent call last):
File "C:\Users\William\Desktop\dbmEditor.py.py", line 35, in <module>
for key in file_edit.keys():
File "C:\Python26\lib\bsddb\__init__.py", line 299, in keys
self._checkOpen()
File "C:\Python26\lib\bsddb\__init__.py", line 250, in _checkOpen
raise error, "BSDDB object has already been closed"
DBError: BSDDB object has already been closed
This is fine and well but I need to do some error handling, but I do not know the syntax. Here is something like I would like it to look like:
if command[0] == 'display':
try:
for key in file_edit.keys():
print repr(key), repr(file_edit[key])
except DBError:
print 'No file open'
but this does not work. Following is the whole code:
import anydbm
import tkFileDialog
while True:
command = raw_input('> ')
command = command.split(' ')
if command[0] == 'open':
file_edit = command[1]
file_edit = anydbm.open(file_edit, 'c')
if command[0] == 'opendialog':
file_edit = tkFileDialog.askopenfilename()
file_edit = anydbm.open(file_edit, 'c')
if command[0] == 'close':
file_edit.close
if command[0] == 'display':
try:
for key in file_edit.keys():
print repr(key), repr(file_edit[key])
except DBError:
print 'No file open'
if command[0] == 'add':
file_edit[command[1]] = command[2]
if command[0] == 'remove':
ask = raw_input('Remove entry? (y/n)')
if ask == 'y':
del file_edit[command[1]]
print 'Entry Removed'
if command[0] == 'close':
file_edit.close()
if command[0] == 'exit':
exit()