Run shell commands synchronously in your sandbox. Commands execute and return results immediately, making them perfect for quick operations, package installation, and system tasks.
Overview
Synchronous command execution is ideal for:
- Quick shell commands and system operations
- Package installation (pip, npm, apt, etc.)
- File system operations
- Environment setup and configuration
- Commands that complete in seconds or minutes
Commands run in /bin/sh by default. For commands that complete quickly, synchronous execution is simpler than background execution.
Basic Command Execution
Run a simple shell command:
from hopx_ai import Sandbox
sandbox = Sandbox.create(template="code-interpreter")
# Run a simple command
result = sandbox.commands.run('ls -la /workspace')
print(result.stdout)
print(f"Exit code: {result.exit_code}")
sandbox.kill()
Expected Output:total 8
drwxr-xr-x 2 root root 4096 Jan 27 10:30 .
drwxr-xr-x 3 root root 4096 Jan 27 10:30 ..
Exit code: 0
Command Result
The CommandResult object contains:
stdout - Standard output from command
stderr - Standard error output (if any)
exit_code - Exit code (0 = success, non-zero = error)
success - Boolean indicating if command succeeded
execution_time - Time taken in seconds
from hopx_ai import Sandbox
sandbox = Sandbox.create(template="code-interpreter")
result = sandbox.commands.run('echo "Hello, World!"')
# 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"Execution time: {result.execution_time}s")
sandbox.kill()
Expected Output:Output: Hello, World!
Errors:
Success: True
Exit code: 0
Execution time: 0.15s
Package Installation
Install packages using package managers:
from hopx_ai import Sandbox
sandbox = Sandbox.create(template="code-interpreter")
# Install Python packages
result = sandbox.commands.run('pip install requests pandas numpy', timeout=300)
if result.success:
print("Packages installed successfully")
print(result.stdout)
else:
print(f"Installation failed: {result.stderr}")
# Install Node.js packages
result = sandbox.commands.run('npm install express lodash', timeout=300)
print(f"npm install exit code: {result.exit_code}")
sandbox.kill()
Expected Output:Packages installed successfully
Successfully installed requests-2.31.0 pandas-2.1.0 numpy-1.24.3
npm install exit code: 0
Environment Variables
Pass environment variables to commands:
from hopx_ai import Sandbox
sandbox = Sandbox.create(template="code-interpreter")
# Run command with environment variables
result = sandbox.commands.run(
'echo $API_KEY',
env={"API_KEY": "sk-123", "DEBUG": "true"}
)
print(result.stdout) # "sk-123"
# Use environment variables in commands
result = sandbox.commands.run(
'python -c "import os; print(os.getenv(\'API_KEY\'))"',
env={"API_KEY": "sk-456"}
)
print(result.stdout) # "sk-456"
sandbox.kill()
Expected Output:
Environment variables passed to commands.run() 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")
# Create directory
sandbox.files.mkdir('/workspace/myproject')
# Run command in specific directory
result = sandbox.commands.run(
'pwd',
working_dir='/workspace/myproject'
)
print(result.stdout) # "/workspace/myproject"
# Run multiple commands in same directory
result = sandbox.commands.run(
'touch file.txt && ls -la',
working_dir='/workspace/myproject'
)
print(result.stdout)
sandbox.kill()
Expected Output:/workspace/myproject
total 8
drwxr-xr-x 2 root root 4096 Jan 27 10:30 .
drwxr-xr-x 3 root root 4096 Jan 27 10:30 ..
-rw-r--r-- 1 root root 0 Jan 27 10:30 file.txt
Timeout Configuration
Set timeout for long-running commands:
from hopx_ai import Sandbox
sandbox = Sandbox.create(template="code-interpreter")
# Run command with custom timeout (5 minutes)
result = sandbox.commands.run(
'npm install',
timeout=300
)
print(f"Installation completed: {result.success}")
# For very long operations, use background execution instead
sandbox.kill()
Expected Output:Installation completed: True
Default timeout is 30 seconds. Maximum timeout is typically 300 seconds (5 minutes) for synchronous execution. For longer-running commands, use Background Commands instead.
Error Handling
Handle command execution errors:
from hopx_ai import Sandbox
from hopx_ai.errors import CommandExecutionError, TimeoutError
sandbox = Sandbox.create(template="code-interpreter")
try:
result = sandbox.commands.run('nonexistent-command')
if not result.success:
print(f"Command failed with exit code: {result.exit_code}")
print(f"Error output: {result.stderr}")
else:
print(f"Output: {result.stdout}")
except TimeoutError:
print("Command timed out")
except CommandExecutionError as e:
print(f"Command execution error: {e}")
sandbox.kill()
Expected Output:Command failed with exit code: 127
Error output: /bin/sh: nonexistent-command: command not found
Chaining Commands
Chain multiple commands together:
from hopx_ai import Sandbox
sandbox = Sandbox.create(template="code-interpreter")
# Chain commands with &&
result = sandbox.commands.run('cd /workspace && mkdir test && ls -la')
print(result.stdout)
# Chain with pipes
result = sandbox.commands.run('ls -la /workspace | grep .txt')
print(result.stdout)
# Multiple commands with semicolon
result = sandbox.commands.run('echo "Step 1"; echo "Step 2"; echo "Step 3"')
print(result.stdout)
sandbox.kill()
Expected Output:total 12
drwxr-xr-x 3 root root 4096 Jan 27 10:30 .
drwxr-xr-x 3 root root 4096 Jan 27 10:30 ..
drwxr-xr-x 2 root root 4096 Jan 27 10:30 test
Step 1
Step 2
Step 3
Complete Example
Here’s a complete example showing command execution workflow:
from hopx_ai import Sandbox
sandbox = Sandbox.create(template="code-interpreter")
# Setup project
print("📦 Setting up project...")
result = sandbox.commands.run('mkdir -p /workspace/myproject', timeout=10)
print(f" Create directory: {'✅' if result.success else '❌'}")
# Install dependencies
print("\n📥 Installing dependencies...")
result = sandbox.commands.run(
'pip install requests pandas',
timeout=300,
working_dir='/workspace/myproject'
)
if result.success:
print(" ✅ Dependencies installed")
print(f" Output: {result.stdout[:100]}...")
else:
print(f" ❌ Installation failed: {result.stderr}")
# Create project files
print("\n📝 Creating project files...")
result = sandbox.commands.run(
'echo "import requests" > main.py && echo "import pandas" >> main.py',
working_dir='/workspace/myproject'
)
print(f" Create files: {'✅' if result.success else '❌'}")
# Verify setup
print("\n🔍 Verifying setup...")
result = sandbox.commands.run(
'ls -la && python -c "import requests, pandas; print(\'All imports OK\')"',
working_dir='/workspace/myproject'
)
if result.success:
print(" ✅ Setup complete")
print(f" Output:\n{result.stdout}")
else:
print(f" ❌ Verification failed: {result.stderr}")
sandbox.kill()
Best Practices
1. Use Appropriate Timeouts
Set timeouts based on expected execution time. Default 30 seconds is good for quick commands, but increase for package installations or long 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 commands.
4. Set Working Directory
Use working_dir to run commands in the correct directory context.
5. Use Background for Long Tasks
Next Steps