LoginJoin GenScrap
Back to Public Gallery
From: k1ito-techby k1itoabout 2 months ago

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.


##0) Install & set your key

bash
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)


##1) Minimal stateful sandbox script

python
# 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)
  • You can run shell commands like pip install … via sandbox.commands.run(...). (Hugging Face)
  • You can upload files into the sandbox with sandbox.files.write(path, data) (string/bytes/IO). (e2b.dev)
  • By default, a sandbox has a short idle timeout (~5 minutes) unless you keep using it. (e2b.dev)

##2) (Optional) Pause & resume the same sandbox later

If you want the exact process memory and filesystem to persist (even running kernels), E2B has persistence (public beta):

python
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 continue

This preserves files and memory (variables, processes) between sessions. (e2b.dev)


##3) Useful docs you’ll likely reference

  • Quickstart (API key, first sandbox). (e2b.dev)
  • Python SDK: Sandbox.run_code (stateful cells; result fields). (e2b.dev)
  • Filesystem read/write (Python files.write, files.read, etc.). (e2b.dev)
  • Install custom packages / runtime installs (pip install in sandbox). (e2b.dev)
  • Commands API (shell in sandbox). (e2b.dev)
  • Cookbook examples (more end-to-end Python demos). (GitHub)

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).

About this Scrapbook
See Also

Other scraps from "k1ito-tech"

diskcache

いい選択です 👍 diskcache は ディスクにキャッシュを保存できるライブラリ で、メモリを圧迫せずに大量のデータをキャッシュできます。しかも API がシンプルで、Webアプリや機械学習の前処理結果キャッシュなどにもよく使われます。 --- インストール bash pip inst...

about 1 month ago
#python caching#diskcache+3

Best mcp server development sdk?

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...

about 1 month ago
#model context protocol#mcp sdk+3

# [2508.20722] rStar2-Agent: Agentic Reasoning Technical Report

[2508.20722] rStar2-Agent: Agentic Reasoning Technical Report URL: https://www.arxiv.org/abs/2508.20722 Captured: 2025/9/6 17:39:22 --- Computer ...

about 2 months ago
#agentic reinforcement learning#large language models+3

Daytona Sandbox:開発環境の新たな可能性

Daytona Sandbox:開発環境の新たな可能性 Daytona Sandboxとは Daytona Sandboxは、開発者がクラウド上で瞬時に開発環境を構築・共有できる革新的なプラットフォームです。従来のローカル開発環境の制約を取り払い、どこからでもアクセス可能な統一された開発体験...

about 2 months ago
#daytona#sandbox+3

# Agentic workflow patterns - AWS Prescriptive Guidance

Agentic workflow patterns integrate modular software agents with structured large language model (LLM) workflows, enabling autonomous reasoning and ac...

2 months ago
#aws#agentic ai+3

Amazon EC2 Single GPU P5 instances are now generally available

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/...

2 months ago
#AWS EC2#NVIDIA H100+3

Want to create your own articles?

Get Started