PYTHON

  minte9
REMEMBERS




Shelve

p219 You can save variables to binary shelve files.
 
"""Shelve module:
You can save and restore variables from the hard drive.
New binary files are generated in working directory.
Shelves values don't need to be opened in read or write mode,
they can do both, once opened.
"""
import shelve, os

DIR = os.path.dirname(os.path.realpath(__file__))
FILE = DIR + "/data/vars.shelve"

# Open shelf and write a list variable
SH = shelve.open(FILE)
answers = ['a', 'b', 'c']
SH['answers'] = answers
SH.close()

# Open shelf and add a value
SH = shelve.open(FILE)
answers = list(SH['answers'])
answers.append('d') # Look Here
SH['answers'] = answers
SH.close()

# Open shelf and get values
SH = shelve.open(FILE)
answers = SH['answers']
print(answers[3])
SH.close()

# Tests
assert answers[3] == 'd'
assert answers[:3] == ['a', 'b', 'c']

Dictionaries

 
"""Shelve dictionaries:
Like dictionaries, shelf values have keys() and values() methods
"""
import shelve, sys, os

DIR = os.path.dirname(os.path.realpath(__file__))
FILE = DIR + "/data/dict.shelve"
db = shelve.open(FILE)

dict = db['spanish'] if 'spanish' in db.keys() else {}

if len(sys.argv) == 3: # Command line add item
    if sys.argv[1] == 'add':
        words = sys.argv[2].split(':')
        dict[words[0]] = words[1]

db['spanish'] = dict
print(db['spanish'])
db.close()

# dictionaries.py
# {}
#
# dictionaries.py add one:uno
# {'one': 'uno'}
#
# dictionaries.py add one:uno
# {'one': 'uno', 'two': 'dos'}

Multi Clipboard (A)

p226 You can save new strings in clipboard, with no code modificiations.
 
#!python3
"""Multi-clipboard application.
This program saves every clipboard text under a key.
The .pyw extension means that Python won't open a terminal.
python multi_clipboard.pyw
"""
import shelve, pyperclip, sys, os
DIR = os.path.dirname(os.path.realpath(__file__))
FILE = DIR + "/data/clipboard.shelve"

with shelve.open(FILE) as db:

    dict = db['keywords'] if 'keywords' in db.keys() else {}

    action  = sys.argv[1] if len(sys.argv) == 3 else ''
    keyword = sys.argv[2] if len(sys.argv) == 3 else ''

    if action.lower() == 'load':
        text = dict[sys.argv[2]]
        pyperclip.copy(text)
        print("Text in clipboard: " + text)

    if action.lower() == 'save':
        keyword = sys.argv[2]
        dict[keyword] = pyperclip.paste()

    db['keywords'] = dict
    print(db['keywords'])


# ./multi_clipboard.pyw
# {}
#
# Copy text: AAA
# ./multi_clipboard.pyw save a
# {'a': 'AAA'}
#
# Copy text: BBB
# ./multi_clipboard.pyw save b
# {'a': 'AAA', 'b': 'BBB'}
#
# ./multi_clipboard.pyw load a
# Text in clipboard: AAA

Questions     github Storage
Zip
        A B C D E F
🔔
1/2