Skip to main content
Synchronous execution is the simplest way to run code in a sandbox. The execution blocks until the code completes, then returns the results immediately.

Prerequisites

Before you begin, make sure you have:
  • Active sandbox - A running sandbox (see Creating Sandboxes)
  • Sandbox object - A Sandbox instance connected to your sandbox
  • Code to execute - The code you want to run in the sandbox

Overview

Synchronous execution is ideal for:
  • Quick scripts and computations
  • Code that completes in seconds or minutes
  • When you need immediate results
  • Simple workflows without complex state management
Synchronous execution automatically captures rich outputs (plots, DataFrames) when available. For more control over rich output capture, see Rich Output.

Basic Execution

Execute code and wait for results:
Expected Output:

Execution Result

The ExecutionResult object contains:
  • stdout - Standard output from code execution
  • stderr - Standard error output (if any)
  • exit_code - Exit code (0 = success, non-zero = error)
  • success - Boolean indicating if execution succeeded
  • execution_time - Time taken in seconds
  • rich_outputs - Array of captured rich outputs (plots, DataFrames)
Expected Output:

Language Support

Execute code in different languages:

Environment Variables

Pass environment variables for execution:
Environment variables passed to run_code() have priority over global environment variables set via sandbox.env.set(). Priority: Request env > Global env > Agent env.

Working Directory

Specify a custom working directory:

Timeout Configuration

Set execution timeout for long-running code:
Default timeout is 60 seconds. Maximum timeout is 300 seconds (5 minutes) for synchronous execution. For longer-running code, use Background Execution or Async Webhooks.

Error Handling

Handle execution errors:

Complete Example

Here’s a complete example showing all features:

Best Practices

1

1. Use Appropriate Timeouts

Set timeouts based on expected execution time. Default 60 seconds is good for quick scripts, but increase for longer operations.
2

2. Handle Errors Gracefully

Always check result.success and handle stderr appropriately. Use try/catch for exception handling.
3

3. Use Environment Variables

Pass environment variables via env parameter rather than hardcoding values in code.
4

4. Check Execution Time

Monitor execution_time to optimize code performance and identify slow operations.
5

5. Use Background for Long Tasks

For code that runs longer than 5 minutes, use Background Execution instead.

Implementation

Next Steps