[Synopsis-changes] Synopsis/Synopsis/Synopsis/Core Processor.py,NONE,1.1

Stefan Seefeld stefan at synopsis.fresco.org
Thu Oct 30 05:54:38 UTC 2003


Update of /cvs/synopsis/Synopsis/Synopsis/Core
In directory frida:/tmp/cvs-serv8010/Synopsis/Core

Added Files:
	Processor.py 
Log Message:
add Processor base class

--- NEW FILE: Processor.py ---
# $Id: Processor.py,v 1.1 2003/10/30 05:54:36 stefan Exp $
#
# Copyright (C) 2003 Stefan Seefeld
# All rights reserved.
# Licensed to the public under the terms of the GNU GPL (>= 2),
# see the file COPYING for details.
#

import sys

class Processor(object):
   """Processor overrides the __new__ operator
   for automatic attribute instantiation.
   All class attributes of type Processor (or lists or tuples thereof)
   found in any base class of the given type are instantiated and assigned
   to instance attributes of the same name for the newly created instance,
   thus overriding the old value.
   This, together with the __init__ function that sets instance attributes
   directly, unifies the different ways to configure processors. Either
   an option is overridden as a class attribute set in a customized sub-class,
   or it is passed as a named value to the constructor."""
    
   def __new__(cls, *args, **kwds):
      """Initialize the instance attribute dictionary such that attributes
      of type 'Processor' are replaced by Processor objects."""
      dictionary = {}
      # iterate over all base classes, starting on the root
      hier = list(cls.__mro__[:])
      hier.reverse()
      for c in hier:
         for name, value in c.__dict__.items():

            # skip privates
            if name.startswith("_"): continue

            # if this is a processor, instantiate it
            if (type(value) == type and issubclass(value, Processor)):
                    
               dictionary[name] = value()

            # if this is a list or tuple containing
            # at least one processor, instantiate the whole list
            elif ((type(value) == list or type(value) == tuple)
                  and filter(lambda item:(type(item) == type
                                          and issubclass(item, Processor)),
                             value)):

               # generate a new list, replacing all Processor types
               # by their respective instances...
               new_list = map(lambda item:(type(item) == type
                                           and issubclass(item, Processor)
                                           and item()
                                           or item),
                              value)
               dictionary[name] = new_list

            # if there already is an entry from a base class
            # override it, no matter the type
            elif name in dictionary:
                
               dictionary[name] = value
                    
      instance = object.__new__(cls)
      instance.__dict__.update(dictionary)
      return instance

   verbose=False

   def __init__(self, **kwds):
      """Use named values to override default attributes."""
      self.__dict__.update(kwds);

   def process(self, **kwds):
      """provide the processor specific code here"""
      self.__dict__.update(kwds);

def error(msg):
   """Write an error message and exit."""
   sys.stderr.write(msg)
   sys.stderr.write('\n')
   sys.exit(-1)

def process(**kwds):
   """Define the entry point to synopsis.
   Call this at the end of the frontend script, passing named processors
   that can be called by name such as:

   python synopsis.py parse arg1=value1
   """
   if len(sys.argv) < 2:
      print 'usage : %s <command> [args]'%sys.argv[0]
      sys.exit(-1)

   command = sys.argv[1]
   props = {}
   args = sys.argv[2:]
   while args and args[0].find('=') != -1:
      l = args[0].split('=')
      if len(l) < 2:
         raise Error, 'argument "%s" not propname=value'%args[0]
      key, value = l[0], '='.join(l[1:])
      if value:
         try:
            props[key] = eval(value)
         except:
            error("""an error occured trying to evaluate \'%s\'
to pass this as a string, please use %s="'%s'" """%(value, key, value))
      else:
         props[key] = None
      args = args[1:]

   # remaining arguments are mapped to the 'input' value,
   # if that is not yet defined
   if args and 'input' not in props:
      props['input'] = args

   if command in kwds:
      try:
         kwds[command].process(**props)
      except KeyError, e:
         error('missing argument "%s"'%e)
   else:
      error('no command "%s"'%command)

#
# $Log: Processor.py,v $
# Revision 1.1  2003/10/30 05:54:36  stefan
# add Processor base class
#





More information about the Synopsis-changes mailing list