> ## 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](/core-concepts/sandboxes/creating))
* **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](/core-concepts/code-execution/rich-output).
</Note>

## Basic Execution

Execute code and wait for results:

<Tabs>
  <Tab title="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>

  <Tab title="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
    ```
  </Tab>
</Tabs>

## 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)

<Tabs>
  <Tab title="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>

  <Tab title="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
    ```
  </Tab>
</Tabs>

## Language Support

Execute code in different languages:

<Tabs>
  <Tab title="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>

  <Tab title="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();
    ```
  </Tab>
</Tabs>

## Environment Variables

Pass environment variables for execution:

<Tabs>
  <Tab title="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>

  <Tab title="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();
    ```
  </Tab>
</Tabs>

<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.
</Note>

## Working Directory

Specify a custom working directory:

<Tabs>
  <Tab title="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>

  <Tab title="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();
    ```
  </Tab>
</Tabs>

## Timeout Configuration

Set execution timeout for long-running code:

<Tabs>
  <Tab title="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>

  <Tab title="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();
    ```
  </Tab>
</Tabs>

<Warning>
  Default timeout is 60 seconds. Maximum timeout is 300 seconds (5 minutes) for synchronous execution. For longer-running code, use [Background Execution](/core-concepts/code-execution/background) or [Async Webhooks](/core-concepts/code-execution/async-webhooks).
</Warning>

## Error Handling

Handle execution errors:

<Tabs>
  <Tab title="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>

  <Tab title="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();
    ```
  </Tab>
</Tabs>

## Complete Example

Here's a complete example showing all features:

<Tabs>
  <Tab title="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>

  <Tab title="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();
    ```
  </Tab>
</Tabs>

## Best Practices

<Steps>
  <Step title="1. Use Appropriate Timeouts">
    Set timeouts based on expected execution time. Default 60 seconds is good for quick scripts, but increase for longer operations.
  </Step>

  <Step title="2. Handle Errors Gracefully">
    Always check `result.success` and handle `stderr` appropriately. Use try/catch for exception handling.
  </Step>

  <Step title="3. Use Environment Variables">
    Pass environment variables via `env` parameter rather than hardcoding values in code.
  </Step>

  <Step title="4. Check Execution Time">
    Monitor `execution_time` to optimize code performance and identify slow operations.
  </Step>

  <Step title="5. Use Background for Long Tasks">
    For code that runs longer than 5 minutes, use [Background Execution](/core-concepts/code-execution/background) instead.
  </Step>
</Steps>

## Implementation

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

## Related

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

## Next Steps

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