import os import re from .CronFile import CronFile class Parser: def parse(self): cronFile = CronFile() crontab = "" with os.popen("crontab -l") as stream: crontab = stream.read() result = crontab begin = re.search("^\s*#\s*BEGIN\((\w+)\).*$", crontab, flags=re.MULTILINE) while begin: section = begin.group(1) cronFile.add_fragment(None, crontab[:begin.span()[0]]) crontab = crontab[begin.span()[1]:] end = re.search("^\s*#\s*END\({0}\).*$".format(section), crontab, flags=re.MULTILINE) if end: cronFile.add_fragment(section, crontab[:end.span()[0]]) crontab = crontab[end.span()[1]:] begin = re.search("^\s*#\s*BEGIN\((\w+)\).*$", crontab, flags=re.MULTILINE) cronFile.add_fragment(None, crontab) return cronFile def render(self, cronFile): result = "" for fragment in cronFile.fragments: if fragment[0] is None: result += fragment[1] else: result += "\n# BEGIN({0})".format(fragment[0]) result += fragment[1] result += "\n# END({0})\n".format(fragment[0]) return result