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:
  • Python
  • JavaScript
from hopx_ai import Sandbox

sandbox = Sandbox.create(template="code-interpreter")

# Execute simple code
result = sandbox.run_code('print("Hello, World!")')

print(result.stdout)  # "Hello, World!\n"
print(f"Success: {result.success}")
print(f"Exit code: {result.exit_code}")
print(f"Execution time: {result.execution_time}s")

sandbox.kill()
Expected Output:
Hello, World!

Success: True
Exit code: 0
Execution time: 1.23s

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)
  • Python
  • JavaScript
from hopx_ai import Sandbox

sandbox = Sandbox.create(template="code-interpreter")

result = sandbox.run_code('''
import sys
print("Python version:", sys.version)
print("Platform:", sys.platform)
''')

# Access all result fields
print(f"Output: {result.stdout}")
print(f"Errors: {result.stderr}")
print(f"Success: {result.success}")
print(f"Exit code: {result.exit_code}")
print(f"Time: {result.execution_time}s")
print(f"Rich outputs: {len(result.rich_outputs)}")

sandbox.kill()
Expected Output:
Output: Python version: 3.11.0 (main, Oct 24 2023, 00:00:00) [GCC 11.3.0]
Platform: linux

Errors: 
Success: True
Exit code: 0
Time: 1.45s
Rich outputs: 0

Language Support

Execute code in different languages:
  • Python
  • JavaScript
from hopx_ai import Sandbox

sandbox = Sandbox.create(template="code-interpreter")

# Python
result = sandbox.run_code('print("Hello from Python!")', language='python')
print(result.stdout)

# JavaScript
result = sandbox.run_code('console.log("Hello from JavaScript!")', language='javascript')
print(result.stdout)

# Bash
result = sandbox.run_code('echo "Hello from Bash!"', language='bash')
print(result.stdout)

sandbox.kill()

Environment Variables

Pass environment variables for execution:
  • Python
  • JavaScript
from hopx_ai import Sandbox

sandbox = Sandbox.create(template="code-interpreter")

# Execute with environment variables
result = sandbox.run_code(
    'import os; print(os.getenv("API_KEY"))',
    language='python',
    env={"API_KEY": "sk-123", "DEBUG": "true"}
)

print(result.stdout)  # "sk-123"

sandbox.kill()
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
from hopx_ai import Sandbox

sandbox = Sandbox.create(template="code-interpreter")

# Execute in custom directory
result = sandbox.run_code(
    'import os; print(os.getcwd())',
    language='python',
    working_dir='/tmp/myproject'
)

print(result.stdout)  # "/tmp/myproject"

sandbox.kill()

Timeout Configuration

Set execution timeout for long-running code:
  • Python
  • JavaScript
from hopx_ai import Sandbox

sandbox = Sandbox.create(template="code-interpreter")

# Execute with custom timeout (5 minutes)
result = sandbox.run_code(
    'import time; time.sleep(10); print("Done")',
    language='python',
    timeout=300  # 5 minutes
)

print(result.stdout)

sandbox.kill()
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:
  • Python
  • JavaScript
from hopx_ai import Sandbox
from hopx_ai.errors import CodeExecutionError, TimeoutError

sandbox = Sandbox.create(template="code-interpreter")

try:
    result = sandbox.run_code('print(undefined_var)', language='python')
    
    if not result.success:
        print(f"Execution failed with exit code: {result.exit_code}")
        print(f"Error output: {result.stderr}")
    else:
        print(f"Output: {result.stdout}")
        
except TimeoutError:
    print("Execution timed out")
except CodeExecutionError as e:
    print(f"Execution error: {e}")

sandbox.kill()

Complete Example

Here’s a complete example showing all features:
  • Python
  • JavaScript
from hopx_ai import Sandbox

# Create sandbox
sandbox = Sandbox.create(template="code-interpreter")

# Execute code with all options
result = sandbox.run_code(
    '''
import os
import sys

print(f"Python: {sys.version}")
print(f"Working directory: {os.getcwd()}")
print(f"API key: {os.getenv('API_KEY', 'not set')}")
print(f"Debug mode: {os.getenv('DEBUG', 'false')}")
''',
    language='python',
    timeout=120,
    env={
        "API_KEY": "sk-123",
        "DEBUG": "true"
    },
    working_dir='/workspace'
)

# Check results
if result.success:
    print("✅ Execution successful")
    print(f"Output:\n{result.stdout}")
else:
    print("❌ Execution failed")
    print(f"Error: {result.stderr}")
    print(f"Exit code: {result.exit_code}")

print(f"Execution time: {result.execution_time}s")

# Cleanup
sandbox.kill()

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