home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 15 / AACD15.ISO / AACD / Programming / Python2 / Python20_source / Tools / modulator / varsubst.py < prev   
Encoding:
Python Source  |  2000-10-25  |  1.6 KB  |  62 lines

  1. #
  2. # Variable substitution. Variables are $delimited$
  3. #
  4. import string
  5. import regex
  6. import regsub
  7.  
  8. error = 'varsubst.error'
  9.  
  10. class Varsubst:
  11.     def __init__(self, dict):
  12.         self.dict = dict
  13.         self.prog = regex.compile('\$[a-zA-Z0-9_]*\$')
  14.         self.do_useindent = 0
  15.  
  16.     def useindent(self, onoff):
  17.         self.do_useindent = onoff
  18.         
  19.     def subst(self, str):
  20.         rv = ''
  21.         while 1:
  22.             pos = self.prog.search(str)
  23.             if pos < 0:
  24.                 return rv + str
  25.             if pos:
  26.                 rv = rv + str[:pos]
  27.                 str = str[pos:]
  28.             len = self.prog.match(str)
  29.             if len == 2:
  30.                 # Escaped dollar
  31.                 rv = rv + '$'
  32.                 str = str[2:]
  33.                 continue
  34.             name = str[1:len-1]
  35.             str = str[len:]
  36.             if not self.dict.has_key(name):
  37.                 raise error, 'No such variable: '+name
  38.             value = self.dict[name]
  39.             if self.do_useindent and '\n' in value:
  40.                 value = self._modindent(value, rv)
  41.             rv = rv + value
  42.  
  43.     def _modindent(self, value, old):
  44.         lastnl = string.rfind(old, '\n', 0) + 1
  45.         lastnl = len(old) - lastnl
  46.         sub = '\n' + (' '*lastnl)
  47.         return regsub.gsub('\n', sub, value)
  48.  
  49. def _test():
  50.     import sys
  51.     import os
  52.  
  53.     sys.stderr.write('-- Copying stdin to stdout with environment map --\n')
  54.     c = Varsubst(os.environ)
  55.     c.useindent(1)
  56.     d = sys.stdin.read()
  57.     sys.stdout.write(c.subst(d))
  58.     sys.exit(1)
  59.  
  60. if __name__ == '__main__':
  61.     _test()
  62.