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:
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
import { Sandbox } from '@hopx-ai/sdk';
const sandbox = await Sandbox.create({ template: 'code-interpreter' });
// Execute simple code
const result = await sandbox.runCode('print("Hello, World!")');
console.log(result.stdout); // "Hello, World!\n"
console.log(`Success: ${result.success}`);
console.log(`Exit code: ${result.exitCode}`);
console.log(`Execution time: ${result.executionTime}s`);
await 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)
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
import { Sandbox } from '@hopx-ai/sdk';
const sandbox = await Sandbox.create({ template: 'code-interpreter' });
const result = await sandbox.runCode(`
import sys
print("Python version:", sys.version)
print("Platform:", sys.platform)
`);
// Access all result fields
console.log(`Output: ${result.stdout}`);
console.log(`Errors: ${result.stderr}`);
console.log(`Success: ${result.success}`);
console.log(`Exit code: ${result.exitCode}`);
console.log(`Time: ${result.executionTime}s`);
console.log(`Rich outputs: ${result.richOutputs?.length || 0}`);
await 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:
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()
import { Sandbox } from '@hopx-ai/sdk';
const sandbox = await Sandbox.create({ template: 'code-interpreter' });
// Python
let result = await sandbox.runCode('print("Hello from Python!")', { language: 'python' });
console.log(result.stdout);
// JavaScript
result = await sandbox.runCode('console.log("Hello from JavaScript!")', { language: 'javascript' });
console.log(result.stdout);
// Bash
result = await sandbox.runCode('echo "Hello from Bash!"', { language: 'bash' });
console.log(result.stdout);
await sandbox.kill();
Environment Variables
Pass environment variables for execution:
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()
import { Sandbox } from '@hopx-ai/sdk';
const sandbox = await Sandbox.create({ template: 'code-interpreter' });
// Execute with environment variables
const result = await sandbox.runCode(
'import os; print(os.getenv("API_KEY"))',
{
language: 'python',
env: { API_KEY: 'sk-123', DEBUG: 'true' }
}
);
console.log(result.stdout); // "sk-123"
await 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:
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()
import { Sandbox } from '@hopx-ai/sdk';
const sandbox = await Sandbox.create({ template: 'code-interpreter' });
// Execute in custom directory
const result = await sandbox.runCode(
'import os; print(os.getcwd())',
{
language: 'python',
workingDir: '/tmp/myproject'
}
);
console.log(result.stdout); // "/tmp/myproject"
await sandbox.kill();
Timeout Configuration
Set execution timeout for long-running code:
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()
import { Sandbox } from '@hopx-ai/sdk';
const sandbox = await Sandbox.create({ template: 'code-interpreter' });
// Execute with custom timeout (5 minutes)
const result = await sandbox.runCode(
'import time; time.sleep(10); print("Done")',
{
language: 'python',
timeout: 300 // 5 minutes
}
);
console.log(result.stdout);
await sandbox.kill();
Error Handling
Handle execution errors:
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()
import { Sandbox } from '@hopx-ai/sdk';
import { CodeExecutionError, TimeoutError } from '@hopx-ai/sdk';
const sandbox = await Sandbox.create({ template: 'code-interpreter' });
try {
const result = await sandbox.runCode('print(undefined_var)', { language: 'python' });
if (!result.success) {
console.error(`Execution failed with exit code: ${result.exitCode}`);
console.error(`Error output: ${result.stderr}`);
} else {
console.log(`Output: ${result.stdout}`);
}
} catch (error) {
if (error instanceof TimeoutError) {
console.error('Execution timed out');
} else if (error instanceof CodeExecutionError) {
console.error(`Execution error: ${error.message}`);
}
}
await sandbox.kill();
Complete Example
Here’s a complete example showing all features:
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()
import { Sandbox } from '@hopx-ai/sdk';
// Create sandbox
const sandbox = await Sandbox.create({ template: 'code-interpreter' });
// Execute code with all options
const result = await sandbox.runCode(
`
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'
},
workingDir: '/workspace'
}
);
// Check results
if (result.success) {
console.log('✅ Execution successful');
console.log(`Output:\n${result.stdout}`);
} else {
console.error('❌ Execution failed');
console.error(`Error: ${result.stderr}`);
console.error(`Exit code: ${result.exitCode}`);
}
console.log(`Execution time: ${result.executionTime}s`);
// Cleanup
await sandbox.kill();
Best Practices
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. Handle Errors Gracefully
Always check result.success and handle stderr appropriately. Use try/catch for exception handling.
3. Use Environment Variables
Pass environment variables via env parameter rather than hardcoding values in code.
4. Check Execution Time
Monitor execution_time to optimize code performance and identify slow operations.
5. Use Background for Long Tasks
Implementation
Next Steps