Documentation Index
Fetch the complete documentation index at: https://mintlify.com/cloudflare/sandbox-sdk/llms.txt
Use this file to discover all available pages before exploring further.
Executes code in an isolated context and returns structured results including output, errors, and visualizations.
Method Signature
async runCode(
code: string,
options?: RunCodeOptions
): Promise<Execution>
Parameters
Execution options
Context to run the code in. If not provided, uses default context for the language.
language
'python' | 'javascript' | 'typescript'
default:"'python'"
Language to use if context is not provided
envVars
Record<string, string | undefined>
Environment variables for this execution. Undefined values are skipped.
Execution timeout in milliseconds
AbortSignal for cancelling execution
onStdout
(output: OutputMessage) => void
Callback for stdout output
onStderr
(output: OutputMessage) => void
Callback for stderr output
Callback for execution results (charts, tables, etc)
onError
(error: ExecutionError) => void
Callback for execution errors
Returns
The execution result
The code that was executed
The context used for execution
Array of execution results (charts, tables, formatted output)
Execution count (for interpreter)
Example
import { getSandbox } from '@cloudflare/sandbox';
const sandbox = getSandbox(env.SANDBOX, 'my-sandbox');
// Execute Python code
const execution = await sandbox.runCode(`
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.title('Sine Wave')
plt.show()
`);
// Access results
console.log('Stdout:', execution.logs.stdout);
console.log('Charts:', execution.results.length);
if (execution.results[0]?.chart) {
console.log('Chart type:', execution.results[0].chart.type);
console.log('Chart image:', execution.results[0].png);
}
// Handle errors
if (execution.error) {
console.error('Error:', execution.error.message);
console.error('Traceback:', execution.error.traceback);
}
Example with Streaming
const execution = await sandbox.runCode(
'print("Hello")',
{
language: 'python',
onStdout: (output) => {
console.log('Stdout:', output.text);
},
onResult: (result) => {
if (result.chart) {
console.log('Received chart:', result.chart.type);
}
},
onError: (error) => {
console.error('Error:', error.message);
}
}
);
Notes
- Automatically creates a default context if none is provided
- Supports multiple result formats: text, HTML, images (PNG/JPEG/SVG), charts, JSON
- Chart detection works with matplotlib, plotly, altair, and seaborn
- Results are structured for easy rendering in UIs
- Use callbacks for real-time output processing
- Context state persists between executions
See Also