Skip to content

Running code

Each sandbox runs a stateful IPython kernel — the same code-interpreter model as a notebook. Variables, imports, and state persist across calls in the same sandbox.

Rich, typed results

run_code returns an Execution with:

  • results — a list of rich outputs. Each can carry text, html, markdown, svg, png (base64), jpeg, pdf, latex, json. The cell's return value is flagged is_main_result.
  • logs{ stdout: [...], stderr: [...] }.
  • error{ name, value, traceback } or null.
  • text — convenience: the main result's text.
python
execution = sbx.run_code("""
import matplotlib.pyplot as plt
plt.plot([1, 4, 9, 16])
plt.title("squares")
""")

for r in execution.results:
    if r.png:                      # matplotlib figures are captured as PNG
        open("chart.png", "wb").write(base64.b64decode(r.png))

A pandas DataFrame comes back with text (repr) and html (a rendered table). display() calls and inline figures show up as additional results.

Streaming output

Stream stdout/stderr/results live as the cell runs — useful for long tasks and responsive UIs.

python
sbx.run_code(
    "for i in range(3): print(i)",
    on_stdout=lambda t: print("out:", t, end=""),
)
javascript
await sbx.runCode("for i in range(3): print(i)", {
  onStdout: (t) => process.stdout.write(t),
  onStderr: (t) => process.stderr.write(t),
  onResult: (r) => console.log("result", r),
});

The resolved Execution is identical whether or not you stream.

Errors

A raised exception doesn't throw in your SDK call — it comes back structured:

python
execution = sbx.run_code("1 / 0")
if execution.error:
    print(execution.error["name"])       # "ZeroDivisionError"
    print(execution.error["traceback"])

Shell vs. code

run_code runs Python in the kernel. To run shell commands, use commands (sbx.commands.run("pip install requests")).

Sovereign compute for Indian AI — hosted in Mumbai (ap-south-1).