The collection class allows you to persistently monitor a collection of items. It reports on which items are new to the collection, which items have left the collection and the age in seconds of each item in the collection.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | #!/usr/bin/python
import shelve
import time
class collection(object):
def __init__(self, db):
self.db = db
def __call__(self, objects):
# get the current time in seconds
now = time.time()
# create/open the shelve db
d = shelve.open(self.db, 'c')
# find & remove the missing items from the collection
removed = [k for k in d if k not in objects]
for remove in removed:
d.pop(remove)
# find & add new items to the collection
added = [k for k in objects if k not in d]
for obj in added:
d[obj] = now
# build a list of tuples (item + age in seconds)
items = [(k, int((now - d[k]))) for k in d]
d.close()
return removed, added, items
if __name__ == "__main__":
"""
below is just a cooked up sample of how the collection
object can be used
"""
mycollection = collection('mycollection.db')
removed, added, items = mycollection(('b','c','d'))
if removed:
print "\nitem(s) removed from the collection:\n"
for item in removed:
print "\t%s" % item
if added:
print "\nitem(s) added to the collection:\n"
for item in added:
print "\t%s" % item
if items:
print "\nitem(s):\n"
for item in items:
i, age = item
print "\titem: %-12s age: %s" % (i,age)
|
The collection class could be used to persistently monitor files in a directory, nodes in a cluster, messages in a queue, accounts on a system or whatever set of items that you wish to keep track of.