Exported source
import ast, time, signal, traceback
from fastcore.utils import *
get_shell
is like python
, except it also maintains a stateful interpreter, rather than just running a single line of code. This is implemented using IPython, so that must be installed.
Traceback (most recent call last):
File "/var/folders/ss/34z569j921v58v8n1n_8z7h40000gn/T/ipykernel_37260/4058275565.py", line 1, in <module>
try: print(1/0)
~^~
ZeroDivisionError: division by zero
TerminalInteractiveShell.run_cell (cell, timeout=None)
Wrapper for original run_cell
which adds timeout and output capture
@patch
def run_cell(self:TerminalInteractiveShell, cell, timeout=None):
"Wrapper for original `run_cell` which adds timeout and output capture"
if timeout:
def handler(*args): raise TimeoutError()
signal.signal(signal.SIGALRM, handler)
signal.alarm(timeout)
try:
with capture_output() as io: result = self.orig_run(cell)
result.stdout = io.stdout
return result
except TimeoutException as e:
result = self.ExecutionResult(error_before_exec=None, error_in_exec=e)
finally:
if timeout: signal.alarm(0)
get_shell ()
Get a TerminalInteractiveShell
with minimal functionality
def get_shell()->TerminalInteractiveShell:
"Get a `TerminalInteractiveShell` with minimal functionality"
sh = TerminalInteractiveShell()
sh.logger.log_output = sh.history_manager.enabled = False
dh = sh.displayhook
dh.finish_displayhook = dh.write_output_prompt = dh.start_displayhook = lambda: None
dh.write_format_data = lambda format_dict, md_dict=None: None
sh.logstart = sh.automagic = sh.autoindent = False
sh.autocall = 0
sh.system = lambda cmd: None
return sh
Traceback (most recent call last):
File "/Users/jhoward/miniconda3/lib/python3.12/site-packages/IPython/core/interactiveshell.py", line 3577, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-1-338156281413>", line 1, in <module>
raise Exception("blah")
Exception: blah