Prerequisites
Before you begin, make sure you have:- Active sandbox - A running sandbox (see Creating Sandboxes)
- Sandbox object - A
Sandboxinstance 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:- Python
- JavaScript
Execution Result
TheExecutionResult object contains:
stdout- Standard output from code executionstderr- Standard error output (if any)exit_code- Exit code (0 = success, non-zero = error)success- Boolean indicating if execution succeededexecution_time- Time taken in secondsrich_outputs- Array of captured rich outputs (plots, DataFrames)
- Python
- JavaScript
Language Support
Execute code in different languages:- Python
- JavaScript
Environment Variables
Pass environment variables for execution:- Python
- JavaScript
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:- Python
- JavaScript
Timeout Configuration
Set execution timeout for long-running code:- Python
- JavaScript
Error Handling
Handle execution errors:- Python
- JavaScript
Complete Example
Here’s a complete example showing all features:- Python
- JavaScript
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
- SDK: sandbox.run_code() - Python SDK method
- CLI - Command-line interface
- API: POST /execute - VM Agent API endpoint
Related
- Background Execution - Long-running tasks
- Rich Output Capture - Capture plots and visualizations
- Streaming Execution - Real-time output streaming
- Async Execution with Webhooks - Very long-running tasks
Next Steps
- Learn about Rich Output capture for plots and DataFrames
- Explore Background Execution for non-blocking operations
- Discover Streaming Execution for real-time output
- Review Process Management for background processes

