listing10-11.py 799 B

1234567891011121314151617181920212223242526272829303132
  1. # templates.py
  2. import fileinput, re
  3. # Matches fields enclosed in square brackets:
  4. field_pat = re.compile(r'\[(.+?)\]')
  5. # We'll collect variables in this:
  6. scope = {}
  7. # This is used in re.sub:
  8. def replacement(match):
  9. code = match.group(1)
  10. try:
  11. # If the field can be evaluated, return it:
  12. return str(eval(code, scope))
  13. except SyntaxError:
  14. # Otherwise, execute the assignment in the same scope ...
  15. exec code in scope
  16. # ... and return an empty string:
  17. return ''
  18. # Get all the text as a single string:
  19. # (There are other ways of doing this; see Chapter 11)
  20. lines = []
  21. for line in fileinput.input():
  22. lines.append(line)
  23. text = ''.join(lines)
  24. # Substitute all the occurrences of the field pattern:
  25. print(field_pat.sub(replacement, text))