Skip to main content

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

code
string
required
The code to execute
options
RunCodeOptions
Execution options

Returns

Execution
object
The execution result

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