The goal of this project was to create a program that uses the shelf module in order for the user to be able to save copied text under a keyword, and then retrieve it by typing the keyword in the program – which then pastes the text in to the clipboard. As an an addition to this project, the keyword and the text it represents can be deleted by the user. Let’s take a look at the code step by step.
Below is the basic description of the program and the import of the libraries and the modules that we need.
#! python
# updatable_clippy_board.py - a multi-clipboard program.
import sys, pyperclip, shelve
In order to understand how I wanted to structure my code, I created a small table of user input and the actions that will be triggered by it.
user input() | action
#=================================
# [keyword] | shelf name set/called on
# save | fill shelf with clipboard output
# list | prints all shelves
# del | deletes the specified shelf
#1 The shelf file is opened. #2 Here the program checks if the amount of command line arguments matches the expected one in which case the user is reminded of the usage protocols of the program. This is followed by different conditionals for every case of the program.
shelf_file = shelve.open('myshelf') #1
if len(sys.argv) == 3 or len(sys.argv) == 2: #2
if sys.argv[-2] == 'save': #3
print('Name: ', sys.argv[-1])
print('Data: ', pyperclip.paste())
usr_text = pyperclip.paste()
shelf_file[sys.argv[-1]] = usr_text
if sys.argv[-2] == "del":
print(f"I'm going to delete {sys.argv[-1]}")
if str(sys.argv[-1]) in shelf_file:
del shelf_file[sys.argv[-1]]
else:
print("No such file, sorry!")
elif sys.argv[-1] == 'list':
print(list(shelf_file.keys()))
elif sys.argv[-1] in shelf_file.keys():
print(shelf_file[str(sys.argv[-1])])
pyperclip.copy(shelf_file[str(sys.argv[-1])])
else:
print("There is not text for " + sys.argv[-1])
shelf_file.close()
else:
print("Usage: python updatable_clippy_board.pyw list - retrieve all saved keywords")
print(" python updatable_clippy_board.pyw save [keyword] - saves copied text under [keyword]")
print(" python updatable_clippy_board.pyw [keyword] - retrieves text saved under [keyword]")
This exercise was a good way to work with the shelve module and user input in the command line. It helped me learn more about troubleshooting the program in the case of wrong input.