Reputation: 93
I'm trying to delete all items in a shelve file by allowing the user to type "clear" in terminal.
Based on several threads I've read on this website, shelve files generally behave like dictionaries, so the .clear
method and several other approaches should work, and in fact do when I test them out in the interactive shell. But I can't get them to work in my program.
Here's my latest attempt (which worked in the shell):
elif len(sys.argv) == 3 and sys.argv[1].lower() == 'clear':
for key in mcbShelf:
del mcbShelf[key]
Just using del
on mcbShelf also did not work.
My program also has a "list" feature that lists all of the keys stored in the shell.
elif len(sys.argv) == 2:
#list keywords
if sys.argv[1].lower() == 'list':
pyperclip.copy(str(list(mcbShelf.keys())))
When I try python3.5 mcb4.pyw clear
in Terminal, then run python3.5 mcb4.pyw list
, I believe an empty list should be copied to the clipboard. But the list has objects in it.
Any thoughts?
Upvotes: 0
Views: 1314
Reputation: 550
I found 2 ways to deal with this. One is to create a function to delete the files the other is to pull a condition flag based on a argument and name it the same file. This is verified working code.
import shelve
import pyperclip
import sys
import os
mcbShelf = shelve.open('mcb')
command = sys.argv[1].lower()
def remove_files():
mcbShelf.close()
os.remove('mcb.dat')
os.remove('mcb.bak')
os.remove('mcb.dir')
if command == 'save':
mcbShelf[sys.argv[2]] = pyperclip.paste()
elif command == 'list':
pyperclip.copy(", ".join(mcbShelf.keys()))
elif command == 'del':
mcbShelf.close()
# call the flag 'n' Always create a new, empty database
mcbShelf = shelve.open('mcb', flag= 'n')
# or delete the files
remove_files()
else:
pyperclip.copy(mcbShelf[sys.argv[1]])
mcbShelf.close()
Upvotes: 1
Reputation: 11
Looks to me like chapter 8 of automate the boring stuff :) Well, didn't like the coding style of that one. Here is my approach, including delete one, and delete all commands.
import shelve
import pyperclip
import sys
mcbShelf = shelve.open('mcb')
command = sys.argv[1].lower()
if command == 'save':
mcbShelf[sys.argv[2]] = pyperclip.paste()
elif command == 'list':
pyperclip.copy(", ".join(mcbShelf.keys()))
elif command == 'delete':
del mcbShelf[sys.argv[2]]
elif command == 'delete_all':
mcbShelf.clear()
else:
pyperclip.copy(mcbShelf[sys.argv[1]])
mcbShelf.close()
Upvotes: 1