Data Analysis
A common Code Interpreter pattern is to write data into the sandbox and then run analysis, transformation, or visualization code with run_code(). This pattern fits data analysis, report generation, and AI code execution applications.
Write a CSV file and run analysis
Python example:
import os
import textwrap
from e2b_code_interpreter import Sandbox
sandbox = Sandbox.create(
template="code-interpreter-v1",
api_key=os.environ["E2B_API_KEY"],
api_url=os.environ["E2B_API_URL"],
domain=os.environ["E2B_DOMAIN"],
)
try:
sandbox.files.write(
"/tmp/sales.csv",
"month,revenue\n2026-01,120\n2026-02,180\n2026-03,160\n",
)
execution = sandbox.run_code(
textwrap.dedent(
"""
import pandas as pd
df = pd.read_csv("/tmp/sales.csv")
print(df)
df["revenue"].sum()
"""
),
timeout=30,
request_timeout=60,
)
if execution.error:
raise RuntimeError(execution.error)
stdout = "".join(execution.logs.stdout or [])
stderr = "".join(execution.logs.stderr or [])
print("stdout:")
print(stdout.strip())
print("stderr:")
print(stderr.strip())
print("text:")
print(execution.text)
finally:
sandbox.kill()TypeScript example:
import { Sandbox } from "@e2b/code-interpreter";
const sandbox = await Sandbox.create("code-interpreter-v1", {
apiKey: process.env.E2B_API_KEY,
apiUrl: process.env.E2B_API_URL,
domain: process.env.E2B_DOMAIN,
});
try {
await sandbox.files.write(
"/tmp/sales.csv",
"month,revenue\n2026-01,120\n2026-02,180\n2026-03,160\n",
);
const execution = await sandbox.runCode(`
import pandas as pd
df = pd.read_csv("/tmp/sales.csv")
print(df)
df["revenue"].sum()
`, {
timeoutMs: 30_000,
requestTimeoutMs: 60_000,
});
if (execution.error) {
throw new Error(`${execution.error.name}: ${execution.error.value}`);
}
console.log("stdout:");
console.log(execution.logs.stdout.join("").trim());
console.log("stderr:");
console.log(execution.logs.stderr.join("").trim());
console.log("text:");
console.log(execution.text);
} finally {
await sandbox.kill();
}Generate a chart file
sandbox.run_code("""import matplotlib.pyplot as plt; plt.plot([1, 2, 3], [120, 180, 160]); plt.title("Revenue"); plt.savefig("/tmp/revenue.png")""")
content = sandbox.files.read("/tmp/revenue.png", format="bytes")TypeScript example:
await sandbox.runCode(`import matplotlib.pyplot as plt; plt.plot([1, 2, 3], [120, 180, 160]); plt.title("Revenue"); plt.savefig("/tmp/revenue.png")`);
const content = await sandbox.files.read("/tmp/revenue.png", { format: "bytes" });FC Agent Sandbox currently supports only the file-based fallback path for charts. For details, see Charts and Visualizations.
Integrate AI-generated code
Before you pass model-generated code into the sandbox, add basic guardrails on the business side:
Define the path of each data file inside the sandbox.
Limit code runtime, input file size, and output size.
Return
execution.error, stdout, stderr, and rich results to the model or user.Do not write user data, API keys, or long-lived business state into generated code.
Recommendations
Small data files can be written with
sandbox.files.write(). For large files, prefer upload URLs.Analysis code should explicitly read paths inside the sandbox, such as
/tmp/input.csv.For charts and report files, write them to
/tmpand then download them. For tables and text results, read fromexecution.resultsor output files.Call
sandbox.kill()when the task is done to avoid holding resources longer than needed.