| 93 | |
| 94 | @staticmethod |
| 95 | def execute( |
| 96 | code, |
| 97 | get_answer_from_stdout = None, |
| 98 | runtime = None, |
| 99 | answer_symbol = None, |
| 100 | answer_expr = None, |
| 101 | timeout_length = 10, |
| 102 | auto_mode=False |
| 103 | ): |
| 104 | try: |
| 105 | if auto_mode: |
| 106 | if "print(" in code[-1]: |
| 107 | program_io = io.StringIO() |
| 108 | with redirect_stdout(program_io): |
| 109 | timeout(timeout_length)(runtime.exec_code)('\n'.join(code)) |
| 110 | program_io.seek(0) |
| 111 | result = program_io.read() |
| 112 | else: |
| 113 | print(code) |
| 114 | timeout(timeout_length)(runtime.exec_code)('\n'.join(code[:-1])) |
| 115 | result = timeout(timeout_length)(runtime.eval_code)(code[-1]) |
| 116 | else: |
| 117 | if get_answer_from_stdout: |
| 118 | program_io = io.StringIO() |
| 119 | with redirect_stdout(program_io): |
| 120 | timeout(timeout_length)(runtime.exec_code)('\n'.join(code)) |
| 121 | program_io.seek(0) |
| 122 | result = program_io.read() |
| 123 | elif answer_symbol: |
| 124 | timeout(timeout_length)(runtime.exec_code)('\n'.join(code)) |
| 125 | result = runtime._global_vars[answer_symbol] |
| 126 | elif answer_expr: |
| 127 | timeout(timeout_length)(runtime.exec_code)('\n'.join(code)) |
| 128 | result = timeout(timeout_length)(runtime.eval_code)(answer_expr) |
| 129 | else: |
| 130 | timeout(timeout_length)(runtime.exec_code)('\n'.join(code[:-1])) |
| 131 | result = timeout(timeout_length)(runtime.eval_code)(code[-1]) |
| 132 | report = "Done" |
| 133 | str(result) |
| 134 | pickle.dumps(result) # serialization check |
| 135 | except: |
| 136 | result = '' |
| 137 | report = traceback.format_exc().split('\n')[-2] |
| 138 | return result, report |
| 139 | |
| 140 | def apply(self, code): |
| 141 | return self.batch_apply([code])[0] |