import os import re import subprocess; from .CronFile import CronFile class Parser: def parse(self): cronFile = CronFile() crontab = "" with subprocess.Popen(["crontab", "-l"], stdout=subprocess.PIPE, encoding="utf-8") as proc: crontab = proc.communicate()[0] 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 update(self, cronFile): with subprocess.Popen(["crontab", "-"], stdin=subprocess.PIPE, encoding="utf-8") as proc: crontab = proc.communicate(self.render(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