# Python Workbench prototype # Basic system for creating and running components # (C)Sky Coyote, June 2007 # List of created components clist = [] # Class functions ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # Basic component type class Component: # Initialize def __init__(self, name): self.name = name self.inputs = [] self.outputs = [] # Add to list clist.append(self) # Update state def run(self): if self.done(): return print "Component.run(): " + self.name # For each input from another component... for index, i in enumerate(self.inputs): if len(i['queue']) > 0: # ...get data... e = i['queue'].pop(0) print self.name + " got " + repr(e) + " from " + i['component'].name # ...and send to another component self.send(index, e) # Print description of state def describe(self): print "name = " + self.name print "inputs:" for i in self.inputs: # Print all fields of inputs print i['component'].name + " " + repr(i['queue']) + " " + \ repr(i['buffer']) print "outputs:" for o in self.outputs: print o.name # Send data to another component by index number def send(self, output, data): if output < len(self.outputs): self.outputs[output].receive(self, data) # Get data from another component (put in intermediate buffer) def receive(self, input, data): for i in self.inputs: if i['component'] == input: i['buffer'].append(data) # Transfer data from intermediate buffers to input queues def update(self): for i in self.inputs: while len(i['buffer']) > 0: i['queue'].append(i['buffer'].pop(0)) # Decide if program shuld stop def done(self): return False # reset state def reset(self): for i in self.inputs: i['queue'] = [] i['buffer'] = [] # Non-class functions ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # Connect components def connect(c1, c2): # Connect to output if not already there if not c2 in c1.outputs: c1.outputs.append(c2) # See if already in input found = False for i in c2.inputs: if i['component'] == c1: found = True if not found: # Creat new input with component, queue, and intermediate buffer c2.inputs.append({'component': c1, 'queue': [], 'buffer': []}) # Run a list of components one or more times def run(iters): if iters < 0: while not done(): run(1) else: for i in range(iters): print '---' for c in clist: # Update state c.run() for c in clist: # Transfer data to input queue c.update() # Reset all components def reset(): for c in clist: c.reset() # Decide if program should stop def done(): result = True for c in clist: if not c.done(): result = False return result # Describe all components in list def describe(): for c in clist: print '---' c.describe()