Execute Python code and capture stdout as well as the full stack trace on error. Forces __name__ = "__main__" so that if __name__ == "__main__": blocks will run. Returns: (output, error) - output: string containing everything that was printed to stdout - err
(code)
| 218 | return run_code(utils_functions + '\n' + code) |
| 219 | |
| 220 | def run_code(code): |
| 221 | """ |
| 222 | Execute Python code and capture stdout as well as the full stack trace on error. |
| 223 | Forces __name__ = "__main__" so that if __name__ == "__main__": blocks will run. |
| 224 | |
| 225 | Returns: |
| 226 | (output, error) |
| 227 | - output: string containing everything that was printed to stdout |
| 228 | - error: string containing the full traceback if an exception occurred; None otherwise |
| 229 | """ |
| 230 | stdout_capture = io.StringIO() |
| 231 | # Provide a globals dict specifying that __name__ is "__main__" |
| 232 | exec_globals = {"__name__": "__main__"} |
| 233 | |
| 234 | with contextlib.redirect_stdout(stdout_capture): |
| 235 | try: |
| 236 | exec(code, exec_globals) |
| 237 | error = None |
| 238 | except Exception: |
| 239 | # Capture the entire stack trace |
| 240 | error = traceback.format_exc() |
| 241 | |
| 242 | output = stdout_capture.getvalue() |
| 243 | return output, error |
| 244 | |
| 245 | |
| 246 | def run_code_from_agent(agent, msg, num_retries=1): |
no outgoing calls
no test coverage detected