1
Curious builder0 XP earned · 300 to level 2
0 daysFinish a lesson to begin
Badge collection0 of 6 unlocked
10 small wins to finish your pathNext lesson →
run_code and the Execution object
run_code streams the cell's output back as JSON messages, and the SDK's parse_output collects them into an Execution: logs, results, an error and a count.
execution = sandbox.run_code("import pandas as pd\ndf = pd.read_csv('orders.csv')\nprint('rows:', len(df))\ndf.total.sum()")The sandbox answers with one JSON message per line. The format is in the SDK's source, _parse_output in e2b_code_interpreter/models.py: stdout and stderr messages for printed text, result for values and displays, error for an exception, and number_of_executions. Feeding those messages to the SDK's own parser builds exactly what run_code returns:
import json
from e2b_code_interpreter.models import Execution, parse_output
execution = Execution()
for message in [
{"type": "stdout", "text": "rows: 3\n", "timestamp": 1},
{"type": "result", "text": "120.5", "is_main_result": True},
{"type": "number_of_executions", "execution_count": 1},
]:
parse_output(execution, json.dumps(message))print(execution)
print(repr(execution.text))
print(execution.logs.stdout)
print(execution.execution_count)logs.stdoutis a list of printed chunks, in order.resultsholds the cell's outputs. The value of the last expression is markedis_main_result, andexecution.textis its text.execution_countis the Jupyter cell number: state is kept betweenrun_codecalls in the same sandbox, like cells in a notebook.
Streaming output
sandbox.run_code(code, on_stdout=lambda message: print("live:", message.line), on_result=lambda result: print("result"))The on_ callbacks are called as each message is parsed, so a UI can show output while long code is still running; the same Execution is still returned at the end.
Try it yourself
- Add a
stderrmessage to the list and printexecution.logs. - Add a second
resultwithoutis_main_resultand printexecution.text. - Call
execution.to_json().
Slow is fine. Stopping is the only problem.