> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hopx.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Synchronous

> Execute code synchronously and wait for results. Learn how to run Python, JavaScript, Bash, and Go code in HopX sandboxes, handle execution results, manage timeouts, and process outputs. Includes SDK examples and REST API endpoints for synchronous code execution.

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](https://docs.hopx.ai/core-concepts/sandboxes/creating.md))
* **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

> [!NOTE]
>
> Synchronous execution automatically captures rich outputs (plots, DataFrames) when available. For more control over rich output capture, see [Rich Output](https://docs.hopx.ai/core-concepts/code-execution/rich-output.md).

## Basic Execution

Execute code and wait for results:

> [tab] Python
>
> ```python theme={null}
> 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
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> 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)

> [tab] Python
>
> ```python theme={null}
> 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
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> 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:

> [tab] Python
>
> ```python theme={null}
> 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()
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> 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:

> [tab] Python
>
> ```python theme={null}
> 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()
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> 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();
> ```

> [!NOTE]
>
> 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:

> [tab] Python
>
> ```python theme={null}
> 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()
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> 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:

> [tab] Python
>
> ```python theme={null}
> 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()
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> 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();
> ```

> [!WARNING]
>
> Default timeout is 60 seconds. Maximum timeout is 300 seconds (5 minutes) for synchronous execution. For longer-running code, use [Background Execution](https://docs.hopx.ai/core-concepts/code-execution/background.md) or [Async Webhooks](https://docs.hopx.ai/core-concepts/code-execution/async-webhooks.md).

## Error Handling

Handle execution errors:

> [tab] Python
>
> ```python theme={null}
> 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()
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> 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:

> [tab] Python
>
> ```python theme={null}
> 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()
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> 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. 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](https://docs.hopx.ai/core-concepts/code-execution/background.md) instead.

## Implementation

* **SDK**: [sandbox.run\_code()](https://docs.hopx.ai/sdk/python/sandbox.md#run_code) - Python SDK method
* **[CLI](https://docs.hopx.ai/cli/introduction.md)** - Command-line interface
* **API**: [POST /execute](https://docs.hopx.ai/api/vm-agent/execute.md) - VM Agent API endpoint

## Related

* **[Background Execution](https://docs.hopx.ai/core-concepts/code-execution/background.md)** - Long-running tasks
* **[Rich Output Capture](https://docs.hopx.ai/core-concepts/code-execution/rich-output.md)** - Capture plots and visualizations
* **[Streaming Execution](https://docs.hopx.ai/core-concepts/code-execution/streaming.md)** - Real-time output streaming
* **[Async Execution with Webhooks](https://docs.hopx.ai/core-concepts/code-execution/async-webhooks.md)** - Very long-running tasks

## Next Steps

* Learn about [Rich Output](https://docs.hopx.ai/core-concepts/code-execution/rich-output.md) capture for plots and DataFrames
* Explore [Background Execution](https://docs.hopx.ai/core-concepts/code-execution/background.md) for non-blocking operations
* Discover [Streaming Execution](https://docs.hopx.ai/core-concepts/code-execution/streaming.md) for real-time output
* Review [Process Management](https://docs.hopx.ai/core-concepts/code-execution/process-management.md) for background processes


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.