Execution Context
Execution contexts preserve variables, imports, the working directory, and interpreter state across multiple code executions. They are useful for multi-step data analysis, interactive code interpreters, and cases where an agent builds code step by step.
Create and use a context
context = sandbox.create_code_context(
cwd="/home/user",
language="python",
request_timeout_ms=60_000,
)
sandbox.run_code("value = 7", context=context)
execution = sandbox.run_code("value * 6", context=context)
print(execution.text)
Common context parameters:
| Parameter | Description |
cwd |
The working directory for code execution. |
language |
The default language for the context, such as python. |
request_timeout_ms / requestTimeoutMs |
Timeout for creating the context or calling the context service, in milliseconds. |
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 {
const context = await sandbox.createCodeContext({
cwd: "/home/user",
language: "python",
requestTimeoutMs: 60_000,
});
await sandbox.runCode("value = 7", { context });
const execution = await sandbox.runCode("value * 6", { context });
console.log(execution.text);
} finally {
await sandbox.kill();
}
List contexts
contexts = sandbox.list_code_contexts()
for context in contexts:
print(context)
TypeScript uses sandbox.listCodeContexts().
Restart a context
Restarting a context clears variables, imports, and interpreter state, but keeps the same context identifier.
context = sandbox.create_code_context()
sandbox.run_code("value = 7", context=context)
sandbox.restart_code_context(context)
You can also pass a context ID. TypeScript uses sandbox.restartCodeContext(context) or sandbox.restartCodeContext(context.contextId).
Remove a context
Delete contexts you no longer need:
context = sandbox.create_code_context()
sandbox.remove_code_context(context)
You can also pass a context ID. TypeScript uses sandbox.removeCodeContext(context) or sandbox.removeCodeContext(context.contextId).
Recommendations
Contexts are suitable only for short-lived computational state. Business-critical state should be written to files, object storage, or an application database. In multi-user scenarios, create a separate context for each session so variables and intermediate results do not interfere with each other.