step-by-step E2B example in Python that shows stateful execution, installing packages, uploading a file, and doing a quick SQLite query—all inside a sandbox.
pip install e2b-code-interpreter python-dotenv
export E2B_API_KEY="e2b_***"E2B’s Python package is e2b-code-interpreter, and the SDK reads your E2B_API_KEY from env. (PyPI)
# e2b_step_by_step.py
import os
from e2b_code_interpreter import Sandbox
def main():
# Spins up an isolated VM ("sandbox"); auto-shuts down when the block exits
with Sandbox() as sbx:
# --- A) Stateful Python: variables persist across calls ---
sbx.run_code("x = 41")
out = sbx.run_code("x += 1; x") # reuses x
print("x =", out.text) # -> 42
# --- B) Shell: install a package inside the sandbox ---
sbx.commands.run("pip install --quiet pandas") # ok to pip-install at runtime
# --- C) Upload a CSV into the sandbox filesystem ---
csv = "name,age\nTaro,30\nHanako,28\n"
sbx.files.write("/home/user/people.csv", csv)
# --- D) Analyze the CSV in Python (pandas) ---
out = sbx.run_code(r'''
import pandas as pd
df = pd.read_csv("/home/user/people.csv")
df["age"].mean()
''')
print("mean age:", out.text)
# --- E) Quick SQLite session (persists objects across cells) ---
sbx.run_code(r'''
import sqlite3
conn = sqlite3.connect("/home/user/demo.db")
cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS t(a INT)")
cur.executemany("INSERT INTO t(a) VALUES (?)", [(1,), (2,), (3,)])
conn.commit()
''')
out = sbx.run_code(r'''
cur.execute("SELECT sum(a) FROM t")
cur.fetchone()[0]
''')
print("sum =", out.text)
# --- F) Peek at files (via Python, no shell needed) ---
out = sbx.run_code('import os; print(os.listdir("/home/user"))')
print("files in /home/user:\n", "".join(out.logs.stdout))
if __name__ == "__main__":
main()Why this works / what to know
Sandbox() starts an isolated cloud VM where you can run code repeatedly and reuse variables (run_code shares state across calls). The returned Execution has .text (last expression) and .logs.stdout for prints. (e2b.dev)pip install … via sandbox.commands.run(...). (Hugging Face)sandbox.files.write(path, data) (string/bytes/IO). (e2b.dev)If you want the exact process memory and filesystem to persist (even running kernels), E2B has persistence (public beta):
from e2b_code_interpreter import Sandbox
sbx = Sandbox() # create
sbx.beta_pause() # save full state (ID: sbx.sandbox_id)
same = Sandbox.connect(sbx.sandbox_id) # resume later and continueThis preserves files and memory (variables, processes) between sessions. (e2b.dev)
Sandbox.run_code (stateful cells; result fields). (e2b.dev)files.write, files.read, etc.). (e2b.dev)pip install in sandbox). (e2b.dev)If you want, I can tailor this to your exact use case (e.g., connecting to Postgres/MySQL from inside the sandbox, or wiring this into your LLM/tool-calling flow).
Popular topics in this scrapbook:
Other scraps from "k1ito-tech"
いい選択です 👍 diskcache は ディスクにキャッシュを保存できるライブラリ で、メモリを圧迫せずに大量のデータをキャッシュできます。しかも API がシンプルで、Webアプリや機械学習の前処理結果キャッシュなどにもよく使われます。 --- インストール bash pip inst...
If by “MCP server” you mean a server implementing the Model Context Protocol (MCP) to allow LLMs / AI agents to interact with external tools/data sour...
[2508.20722] rStar2-Agent: Agentic Reasoning Technical Report URL: https://www.arxiv.org/abs/2508.20722 Captured: 2025/9/6 17:39:22 --- Computer ...
Daytona Sandbox:開発環境の新たな可能性 Daytona Sandboxとは Daytona Sandboxは、開発者がクラウド上で瞬時に開発環境を構築・共有できる革新的なプラットフォームです。従来のローカル開発環境の制約を取り払い、どこからでもアクセス可能な統一された開発体験...
Agentic workflow patterns integrate modular software agents with structured large language model (LLM) workflows, enabling autonomous reasoning and ac...
What's New at AWS - Cloud Innovation & News URL: https://aws.amazon.com/jp/about-aws/whats-new/2025/08/amazon-p5-single-gpu-instances-now-available/...
Want to create your own articles?
Get Started