#!/usr/bin/env python2.3 # $Id: sidb.py,v 1.2 2006-03-09 10:12:10-06 annis Exp $ # $Source: /u/annis/talks_articles/pythontut/RCS/sidb.py,v $ import pwd import os import cPickle import re # Local exceptions: class SIDBTypeError(TypeError): pass class InventoryItem: def __init__(self, hostname, opsys, user, location): self.hostname = hostname self.os = opsys self.user = user self.location = location def __str__(self): try: fullname = pwd.getpwnam(self.user)[4] except KeyError: fullname = "unknown user '%s'" % self.user return "%s (%s), used by %s in %s." % (self.hostname, self.os, fullname, self.location) class InventoryDB: def __init__(self, dbfile): self.dbfile = dbfile # DB itself is list of InventoryItem instances. self.db = [] # Don't save if not necessary. self.need_to_save = False if os.path.exists(dbfile): self.loaddb() def loaddb(self): f = open(self.dbfile, "r") self.db = cPickle.load(f) f.close() def savedb(self): if self.need_to_save: f = open(self.dbfile, "w") cPickle.dump(self.db, f) f.close() self.need_to_save = False def add(self, item): if not isinstance(item, InventoryItem): raise SIDBTypeError, "'%s' not InventoryItem" % item else: self.db.append(item) self.need_to_save = True def select_exact(self, attr, val): return [m for m in self.db if getattr(m, attr) == val] def select_match(self, attr, pattern): answ = [] for item in self.db: match = re.search(pattern, getattr(item, attr), re.IGNORECASE) if match is not None: answ.append(item) return answ def __getitem__(self, hostname): return self.select_exact('hostname', hostname) # EOF