Parser.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import os
  2. import re
  3. import subprocess;
  4. from .CronFile import CronFile
  5. class Parser:
  6. def parse(self):
  7. cronFile = CronFile()
  8. crontab = ""
  9. with subprocess.Popen(["crontab", "-l"], stdout=subprocess.PIPE, encoding="utf-8") as proc:
  10. crontab = proc.communicate()[0]
  11. begin = re.search("^\s*#\s*BEGIN\((\w+)\).*$", crontab, flags=re.MULTILINE)
  12. while begin:
  13. section = begin.group(1)
  14. cronFile.add_fragment(None, crontab[:begin.span()[0]])
  15. crontab = crontab[begin.span()[1]:]
  16. end = re.search("^\s*#\s*END\({0}\).*$".format(section), crontab, flags=re.MULTILINE)
  17. if end:
  18. cronFile.add_fragment(section, crontab[:end.span()[0]])
  19. crontab = crontab[end.span()[1]:]
  20. begin = re.search("^\s*#\s*BEGIN\((\w+)\).*$", crontab, flags=re.MULTILINE)
  21. cronFile.add_fragment(None, crontab)
  22. return cronFile
  23. def update(self, cronFile):
  24. with subprocess.Popen(["crontab", "-"], stdin=subprocess.PIPE, encoding="utf-8") as proc:
  25. crontab = proc.communicate(self.render(cronFile))
  26. def render(self, cronFile):
  27. result = ""
  28. for fragment in cronFile.fragments:
  29. if fragment[0] is None:
  30. result += fragment[1]
  31. else:
  32. result += "\n# BEGIN({0})".format(fragment[0])
  33. result += fragment[1]
  34. result += "\n# END({0})\n".format(fragment[0])
  35. return result