E2BE2B SDK 2.50 · Code Interpreter 2.10 · Python 3.10+
0%
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.

Examplewith a key
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:

Example
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))
Example
print(execution)
print(repr(execution.text))
print(execution.logs.stdout)
print(execution.execution_count)
  • logs.stdout is a list of printed chunks, in order.
  • results holds the cell's outputs. The value of the last expression is marked is_main_result, and execution.text is its text.
  • execution_count is the Jupyter cell number: state is kept between run_code calls in the same sandbox, like cells in a notebook.

Streaming output

Examplewith a key
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 stderr message to the list and print execution.logs.
  • Add a second result without is_main_result and print execution.text.
  • Call execution.to_json().

Slow is fine. Stopping is the only problem.