def evaluate(self, code): log_id = output.new_log() try: try: result = timer.timed(self.timeout, eval, (code, self._frame)) except SyntaxError: timer.timed(self.timeout, exec, (code, self._frame)) result = None except RuntimeError as e: stacktrace_length = 15 stacktrace = traceback.format_exc().strip().split('\n') print('Traceback (most recent call last):\n ...') print('\n'.join(stacktrace[-stacktrace_length:])) raise interpreter.ConsoleException(e) except exceptions.Timeout as e: print( '# Error: evaluation exceeded {} seconds - check for infinite loops' .format(e.timeout)) raise interpreter.ConsoleException(e) except Exception as e: stacktrace = traceback.format_exc() token = '<string>' token_start = stacktrace.rfind(token) index = stacktrace.find('\n', token_start) + 1 stacktrace = stacktrace[index:].rstrip('\n') if '\n' in stacktrace: print('Traceback (most recent call last):') print(stacktrace) raise interpreter.ConsoleException(e) else: printed_output = ''.join(output.get_log(log_id)) return result, debug.remove_debug(printed_output) finally: output.remove_log(log_id)
def evaluate(self, code): if not code.strip(): # scheme.scheme_read can't handle empty strings. return None, '' log_id = output.new_log() try: exp = self.scheme.read_line(code) result = timer.timed(self.timeout, self.scheme.scheme_eval, (exp, self._frame)) except RuntimeError as e: stacktrace_length = 15 stacktrace = traceback.format_exc().strip().split('\n') print('Traceback (most recent call last):\n ...') print('\n'.join(stacktrace[-stacktrace_length:])) raise interpreter.ConsoleException(e) except exceptions.Timeout as e: print('# Error: evaluation exceeded {} seconds.'.format(e.timeout)) raise interpreter.ConsoleException(e) except self.scheme.SchemeError as e: print('# Error: {}'.format(e)) raise interpreter.ConsoleException(e, exception_type='SchemeError') except Exception as e: stacktrace = traceback.format_exc() token = '<module>\n' index = stacktrace.rfind(token) + len(token) stacktrace = stacktrace[index:].rstrip('\n') if '\n' in stacktrace: print('Traceback (most recent call last):') print(stacktrace) raise interpreter.ConsoleException(e) else: printed_output = ''.join(output.get_log(log_id)) return result, printed_output finally: output.remove_log(log_id)
def evaluate_open(self, line): """Subroutine for evaluating a .open command.""" filename = line.replace('.open', '').strip() if ' ' in filename: raise interpreter.ConsoleException( Exception('Invalid usage of .open'), exception_type='Error') if not os.path.exists(filename): raise interpreter.ConsoleException(Exception( 'No such file: {}'.format(filename)), exception_type='Error') return filename
def evaluate_read(self, line): """Subroutine for evaluating a .read command.""" filename = line.replace('.read', '').strip() if ' ' in filename: raise interpreter.ConsoleException( Exception('Invalid usage of .read'), exception_type='Error') if not os.path.exists(filename): raise interpreter.ConsoleException(Exception( 'No such file: {}'.format(filename)), exception_type='Error') with open(filename, 'r') as f: contents = f.read() return re.sub(r'^\.read\s+.*$', lambda m: self.evaluate_read(m.group(0)), contents, flags=re.M)
def _lark_execution_guard(self): log_id = output.new_log() try: yield except exceptions.Timeout as e: print('# Error: evaluation exceeded {} seconds.'.format(e.timeout)) raise interpreter.ConsoleException(e) except (LarkError, UnexpectedEOF) as e: print('# Error: {}'.format(e)) raise interpreter.ConsoleException(e) except Exception as e: stacktrace = traceback.format_exc() token = '<module>\n' index = stacktrace.rfind(token) + len(token) stacktrace = stacktrace[index:].rstrip('\n') if '\n' in stacktrace: print('Traceback (most recent call last):') print(stacktrace) raise interpreter.ConsoleException(e) finally: output.remove_log(log_id)
def _use_sqlite_cli(self, env): """Pipes the test case into the "sqlite3" executable. The method _has_sqlite_cli MUST be called before this method is called. PARAMETERS: env -- mapping; represents shell environment variables. Primarily, this allows modifications to PATH to check the current directory first. RETURNS: (test, expected, result), where test -- str; test input that is piped into sqlite3 expected -- str; the expected output, for display purposes result -- str; the actual output from piping input into sqlite3 """ test = [] expected = [] for line in self._setup + self._code + self._teardown: if isinstance(line, interpreter.CodeAnswer): expected.extend(line.output) elif line.startswith(self.PS1): test.append(line[len(self.PS1):]) elif line.startswith(self.PS2): test.append(line[len(self.PS2):]) test = '\n'.join(test) result, error = (None, None) process = None args = ['sqlite3'] sqlite_shell = get_sqlite_shell() if sqlite_shell: if self.timeout is None: (stdin, stdout, stderr) = (io.StringIO(test), io.StringIO(), io.StringIO()) sqlite_shell.main(*args, stdin=stdin, stdout=stdout, stderr=stderr) result, error = (stdout.getvalue(), stderr.getvalue()) else: args[:] = [sys.executable] + subprocess._args_from_interpreter_flags() + ["--", sqlite_shell.__file__] + args[1:] if result is None: process = subprocess.Popen(args, universal_newlines=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) if process: try: result, error = process.communicate(test, timeout=self.timeout) except subprocess.TimeoutExpired as e: process.kill() print('# Error: evaluation exceeded {} seconds.'.format(self.timeout)) raise interpreter.ConsoleException(exceptions.Timeout(self.timeout)) return test, '\n'.join(expected), (error + '\n' + result).strip()
def evaluate(self, code): if not code.strip(): return code = re.sub(r'(\A|\n)\s*--.*?\n', '', code, re.M) if code.startswith('.'): try: self.evaluate_dot(code) except interpreter.ConsoleException as e: print('Error: {}'.format(e)) raise except self.sqlite3.Error as e: print('Error: {}'.format(e)) raise interpreter.ConsoleException(e, exception_type='Error') return try: cursor = timer.timed(self.timeout, self._conn.execute, (code, )) except exceptions.Timeout as e: print('Error: evaluation exceeded {} seconds.'.format(e.timeout)) raise interpreter.ConsoleException(e) except self.sqlite3.Error as e: print('Error: {}'.format(e)) raise interpreter.ConsoleException(e, exception_type='Error') else: return cursor