Skip to main content
The Commands resource provides shell command execution capabilities for running system commands, scripts, and tools inside sandboxes.

Accessing Commands Resource

from hopx_ai import Sandbox

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

Running Commands

run()

Execute a shell command and wait for completion.
result = sandbox.commands.run('ls -la /workspace')
print(result.stdout)
print(f"Exit code: {result.exit_code}")
Method Signature:
def run(
    self,
    command: str,
    *,
    timeout: int = 30,
    background: bool = False,
    env: Optional[Dict[str, str]] = None,
    working_dir: str = "/workspace",
) -> CommandResult
Parameters:
  • command (str): Shell command to run
  • timeout (int): Command timeout in seconds (default: 30)
  • background (bool): Run in background (returns immediately) (default: False)
  • env (Dict[str, str], optional): Environment variables for this command only
  • working_dir (str): Working directory for command (default: “/workspace”)
Returns: CommandResult object Raises:
  • CommandExecutionError: If command execution fails
  • TimeoutError: If command times out

CommandResult

The CommandResult object contains command execution results:
@dataclass
class CommandResult:
    stdout: str              # Standard output
    stderr: str              # Standard error
    exit_code: int           # Exit code (0 = success)
    execution_time: float    # Execution time in seconds
    
    # Convenience properties
    @property
    def success(self) -> bool:
        """True if exit_code == 0"""
        return self.exit_code == 0
Example:
result = sandbox.commands.run('echo "Hello, World!"')
if result.success:
    print(f"Output: {result.stdout}")
else:
    print(f"Error: {result.stderr}")
    print(f"Exit code: {result.exit_code}")

Basic Usage

Simple Commands

# List files
result = sandbox.commands.run('ls -la')
print(result.stdout)

# Check Python version
result = sandbox.commands.run('python --version')
print(result.stdout)

# Get system info
result = sandbox.commands.run('uname -a')
print(result.stdout)

Commands with Output

# Count files
result = sandbox.commands.run('ls -1 /workspace | wc -l')
file_count = int(result.stdout.strip())
print(f"Found {file_count} files")

# Get disk usage
result = sandbox.commands.run('df -h /workspace')
print(result.stdout)

Timeouts

Set custom timeouts for long-running commands:
# Quick command
result = sandbox.commands.run('ls -la', timeout=10)

# Long-running command
result = sandbox.commands.run('npm install', timeout=300)  # 5 minutes

# Very long command
result = sandbox.commands.run('make build', timeout=1800)  # 30 minutes
Note: The timeout includes both execution time and network overhead.

Working Directory

Execute commands in a specific directory:
# Create project directory
sandbox.files.mkdir('/workspace/project')

# Run command in project directory
result = sandbox.commands.run(
    'ls -la',
    working_dir='/workspace/project'
)

# Initialize git repository
result = sandbox.commands.run(
    'git init',
    working_dir='/workspace/project'
)

Environment Variables

Pass environment variables for a specific command:
# Set API key for this command only
result = sandbox.commands.run(
    'echo $API_KEY',
    env={"API_KEY": "sk-test-123"}
)

# Multiple environment variables
result = sandbox.commands.run(
    'python script.py',
    env={
        "API_KEY": "sk-prod-xyz",
        "DEBUG": "true",
        "NODE_ENV": "production"
    }
)
Environment Variable Priority:
  1. Command-specific env vars (from env parameter)
  2. Global sandbox env vars (from sandbox.env)
  3. Agent default env vars

Background Execution

Run commands in the background:
# Start background process
result = sandbox.commands.run(
    'python long_running_script.py',
    background=True
)

# Command returns immediately
print(f"Process started: {result.stdout}")
Note: Background commands return immediately with process information. Use process management APIs to monitor and control background processes.

Error Handling

Handle command execution errors:
from hopx_ai.errors import CommandExecutionError, TimeoutError

try:
    result = sandbox.commands.run('invalid-command-that-fails')
    if not result.success:
        print(f"Command failed: {result.stderr}")
except CommandExecutionError as e:
    print(f"Command execution failed: {e.message}")
    print(f"Command: {e.command}")
except TimeoutError as e:
    print(f"Command timed out: {e.message}")

Common Use Cases

Package Installation

# Install Python packages
result = sandbox.commands.run('pip install pandas numpy matplotlib', timeout=300)

# Install Node.js packages
result = sandbox.commands.run('npm install express', timeout=180)

# Install system packages
result = sandbox.commands.run('apt-get update && apt-get install -y curl', timeout=300)

File Operations

# Create file
result = sandbox.commands.run('echo "Hello" > /workspace/test.txt')

# Copy files
result = sandbox.commands.run('cp /workspace/file1.txt /workspace/file2.txt')

# Find files
result = sandbox.commands.run('find /workspace -name "*.py"')

Git Operations

# Clone repository
result = sandbox.commands.run(
    'git clone https://github.com/user/repo.git /workspace/repo',
    timeout=120
)

# Check status
result = sandbox.commands.run(
    'git status',
    working_dir='/workspace/repo'
)

# Pull latest changes
result = sandbox.commands.run(
    'git pull',
    working_dir='/workspace/repo'
)

Process Management

# List running processes
result = sandbox.commands.run('ps aux')

# Check if process is running
result = sandbox.commands.run('pgrep -f "python script.py"')
if result.exit_code == 0:
    print("Process is running")
else:
    print("Process not found")

System Information

# Get CPU info
result = sandbox.commands.run('lscpu')

# Get memory info
result = sandbox.commands.run('free -h')

# Get disk usage
result = sandbox.commands.run('df -h')

Best Practices

1. Check Command Success

Always check result.success or result.exit_code:
result = sandbox.commands.run('some-command')
if not result.success:
    print(f"Command failed: {result.stderr}")
    return

2. Use Appropriate Timeouts

# Quick commands
result = sandbox.commands.run('ls -la', timeout=10)

# Package installations
result = sandbox.commands.run('npm install', timeout=300)

# Build processes
result = sandbox.commands.run('make build', timeout=1800)

3. Handle Large Outputs

For commands with large output, consider redirecting to files:
# Instead of capturing all output
result = sandbox.commands.run('find /workspace -type f > /workspace/files.txt')

# Then read the file
files = sandbox.files.read('/workspace/files.txt')

4. Use Environment Variables for Secrets

# Pass secrets via environment variables
result = sandbox.commands.run(
    'python script.py',
    env={"API_KEY": "sk-secret-key"}
)

5. Chain Commands Carefully

# Use && for sequential execution
result = sandbox.commands.run('cd /workspace && npm install && npm test')

# Use || for fallback
result = sandbox.commands.run('command1 || command2')

Examples

Setup Project Environment

# Create project structure
sandbox.files.mkdir('/workspace/project')

# Initialize git
sandbox.commands.run(
    'git init',
    working_dir='/workspace/project'
)

# Install dependencies
sandbox.commands.run(
    'npm install',
    working_dir='/workspace/project',
    timeout=300
)

# Run tests
result = sandbox.commands.run(
    'npm test',
    working_dir='/workspace/project'
)

Data Processing Pipeline

# Download data
sandbox.commands.run(
    'wget https://example.com/data.csv -O /workspace/data.csv',
    timeout=120
)

# Process data
result = sandbox.run_code(
    '''
import pandas as pd
df = pd.read_csv('/workspace/data.csv')
df.to_csv('/workspace/processed.csv', index=False)
'''
)

# Verify output
result = sandbox.commands.run('wc -l /workspace/processed.csv')
print(f"Processed {result.stdout.strip()} lines")

Build and Deploy

# Build application
result = sandbox.commands.run(
    'npm run build',
    working_dir='/workspace/app',
    timeout=600
)

if result.success:
    # Package build artifacts
    sandbox.commands.run(
        'tar -czf /workspace/build.tar.gz dist/',
        working_dir='/workspace/app'
    )
    
    # Download build
    sandbox.files.download('/workspace/build.tar.gz', './build.tar.gz')