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

# Command Execution

> Command execution resource for running shell commands in HopX sandboxes using the Python SDK. Complete reference for the Commands class including methods for running commands synchronously and in the background. Includes code examples for system administration, package installation, and automation tasks.

**Version:** 0.3.0\
**Last Verified:** 2025-01-27\
**Package:** `hopx-ai` on [PyPI](https://pypi.org/project/hopx-ai/)

## Overview

The `Commands` resource provides shell command execution capabilities for sandboxes. Access it via the `commands` property on a `Sandbox` instance. Use this resource when you need to run shell commands, install packages, or execute system utilities.

The `Commands` resource is lazy-loaded and provides synchronous command execution.

## Access

```python theme={null}
from hopx_ai import Sandbox

sandbox = Sandbox.create(template="code-interpreter")
commands = sandbox.commands  # Lazy-loaded
```

## Methods

### `run`

Run a shell command.

```python theme={null}
commands.run(
    command,
    *,
    timeout=30,
    background=False,
    env=None,
    working_dir='/workspace'
) -> CommandResult
```

**Parameters:**

* `command` (`str`): Shell command to execute
* `timeout` (`int`, optional): Command timeout in seconds (default: `30`)
* `background` (`bool`, optional): Run in background (default: `False`)
* `env` (`Dict[str, str]`, optional): Environment variables for command
* `working_dir` (`str`, optional): Working directory (default: `'/workspace'`)

**Returns:** `CommandResult` - Command execution result with `stdout`, `stderr`, `exit_code`, and `execution_time`

**Raises:**

* `CommandExecutionError`: Command execution failed
* `TimeoutError`: Command timed out

**Example:**

```python theme={null}
result = sandbox.commands.run("ls -la /workspace")
print(result.stdout)
print(f"Exit code: {result.exit_code}")
```

**See Also:**

* [API: Run Command](/api/vm-agent/run-command)

***

## CommandResult Model

The `run()` method returns a `CommandResult` object with:

* `stdout` (`str`): Standard output
* `stderr` (`str`): Standard error
* `exit_code` (`int`): Exit code (0 = success)
* `execution_time` (`float`): Execution time in seconds
* `success` (`bool`): Convenience property (`exit_code == 0`)

***

## Examples

### Example 1: Basic Command Execution

```python theme={null}
from hopx_ai import Sandbox

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

# Run a simple command
result = sandbox.commands.run("echo 'Hello, World!'")
print(result.stdout)  # "Hello, World!\n"
print(f"Success: {result.success}")

sandbox.kill()
```

### Example 2: Install Packages

```python theme={null}
from hopx_ai import Sandbox

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

# Install a package
result = sandbox.commands.run("pip install requests")
if result.success:
    print("Package installed successfully")
else:
    print(f"Installation failed: {result.stderr}")

sandbox.kill()
```

### Example 3: Command with Environment Variables

```python theme={null}
from hopx_ai import Sandbox

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

# Run command with custom environment
result = sandbox.commands.run(
    "echo $MY_VAR",
    env={"MY_VAR": "Hello from env"}
)
print(result.stdout)

sandbox.kill()
```

### Example 4: Working Directory

```python theme={null}
from hopx_ai import Sandbox

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

# Create directory
sandbox.files.mkdir("/workspace/my_project")

# Run command in specific directory
result = sandbox.commands.run(
    "pwd",
    working_dir="/workspace/my_project"
)
print(result.stdout)  # "/workspace/my_project\n"

sandbox.kill()
```

### Example 5: Long-Running Commands

```python theme={null}
from hopx_ai import Sandbox

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

# Run command with longer timeout
result = sandbox.commands.run(
    "sleep 10 && echo 'Done'",
    timeout=60
)
print(result.stdout)

sandbox.kill()
```

***

## Related Classes

* **[Sandbox](/sdk/python/sandbox)** - Main sandbox class
* **[Files](/sdk/python/files)** - File operations resource
* **[Models](/sdk/python/models)** - Data models including `CommandResult`

## See Also

* [Core Concepts: Execution](/core-concepts/execution) - Learn about code execution
* [Sandbox Class](/sdk/python/sandbox) - Access commands via `sandbox.commands`

## Related

* **[Running Commands](/core-concepts/commands/running)** - Learn about command execution
* **[Background Commands](/core-concepts/commands/background)** - Run commands in background
* **[API: Command Execution](/api/vm-agent/run-command)** - VM Agent API endpoints

## Next Steps

* Learn about [Running Commands](/core-concepts/commands/running) for synchronous execution
* Explore [Background Commands](/core-concepts/commands/background) for non-blocking tasks
* Review [Code Execution](/core-concepts/code-execution/synchronous) for programmatic execution
* **[CLI Commands](/cli/commands/cmd)** - Execute shell commands from the command line
