PageRenderTime 23ms CodeModel.GetById 0ms RepoModel.GetById 0ms app.codeStats 0ms

/phpy/drafts/phpy_1.py

https://bitbucket.org/arosenthal/python
Python | 71 lines | 60 code | 5 blank | 6 comment | 5 complexity | 8dd2f12e8239946a0509aa8e766676ee MD5 | raw file
  1. #Python Hypertext Preprocessor (First iteration: Not functional)
  2. #Author: Anson Rosenthal (anrosent)
  3. #10/2013
  4. import sys
  5. #next move is to make print statements redirect to capture print output in node
  6. # using AST
  7. # also clean up parser
  8. class ParseNode():
  9. def __init__(self, string, first, delim):
  10. buf = [first]
  11. for c in string:
  12. if c == delim:
  13. break
  14. buf.append(c)
  15. self.string = ''.join(buf)
  16. def generate(self):
  17. pass
  18. class Text(ParseNode):
  19. def __init__(self, string, first, delim):
  20. ParseNode.__init__(self, string, first, delim)
  21. def generate(self):
  22. return self.string
  23. class Code(ParseNode):
  24. def __init__(self, string, first, delim):
  25. ParseNode.__init__(self, string, first, delim)
  26. def generate(self):
  27. return str(eval(self.string))
  28. class PyHPP():
  29. def __init__(self):
  30. self.buffer = None
  31. self.parse_seq = []
  32. self.delim = '#'
  33. self.in_code = False
  34. self.done = False
  35. def parse_full(self, string):
  36. nodes = []
  37. self.in_code = string[0] != self.delim
  38. self.buffer = iter(string)
  39. for c in self.buffer:
  40. if self.in_code:
  41. nodes.append(Text(self.buffer, c, self.delim))
  42. else:
  43. nodes.append(Code(self.buffer, c, self.delim))
  44. self.in_code = not self.in_code
  45. return ''.join(map(lambda node:node.generate(), nodes))
  46. # def advance(self):
  47. # self.buffer.__next__()
  48. # def parse(self,string):
  49. # splits = string.split(self.delim)
  50. # text_first = int((string[0] != self.delim))
  51. # splits[text_first::2] = map(str, map(eval, splits[text_first::2]))
  52. # return ''.join(splits)
  53. if __name__ == '__main__':
  54. with open(sys.argv[1]) as inputfile:
  55. a = PyHPP()
  56. print(a.parse_full(inputfile.read()))