diff options
Diffstat (limited to 'clean.py')
-rw-r--r-- | clean.py | 80 |
1 files changed, 80 insertions, 0 deletions
diff --git a/clean.py b/clean.py new file mode 100644 index 0000000..5d14c4a --- /dev/null +++ b/clean.py @@ -0,0 +1,80 @@ +import os +import shutil +import subprocess +import tempfile +import threading + +class CompileException(Exception): + pass + +class TimeoutException(Exception): + pass + +class KillableThread(): + def __init__(self, *args, **kwargs): + self.popenargs = args + self.kwargs = kwargs + self.kwargs['stdout'] = subprocess.PIPE + self.process = None + self.result = None + + def run(self, timeout=5): + def target(): + self.process = subprocess.Popen(*self.popenargs, **self.kwargs) + try: + self.result = self.process.communicate()[0] + except IOError: + pass + + thread = threading.Thread(target=target) + thread.start() + + thread.join(timeout) + if thread.is_alive(): + self.process.kill() + try: + self.process.communicate() + thread.join() + except IOError: + pass + return self.result + +def compile(module): + with open(os.devnull, 'w') as FNULL: + result = subprocess.call(['clm', module, '-o', module], + stdout=FNULL, stderr=FNULL) + if result != 0: + raise CompileException() + +def run(module): + t = KillableThread(['./' + module, '-nt']) + result = t.run() + if result == None: + raise TimeoutException() + else: + return result[:-1] + +def cleanup(module): + if os.path.exists('Clean System Files'): + shutil.rmtree('Clean System Files') + if os.path.exists(module + '.icl'): + os.unlink(module + '.icl') + if os.path.exists(module): + os.unlink(module) + +def gettempfile(): + tf = tempfile.mkstemp(dir='.', suffix='.icl')[1] + return os.path.basename(tf)[:-4], tf + +def single_command(cmd): + base_format = 'module %s\nimport StdEnv\nStart = %s\n' + + module, fn = gettempfile() + with open(fn, 'w') as f: + f.write(base_format % (module, cmd)) + + compile(module) + output = run(module) + cleanup(module) + + return output |