Skip to main content
This guide covers executing shell commands in Hopx Sandboxes, including basic commands, piped commands, package installation, and background execution.

Basic Command Execution

Run simple shell commands:
  • Python
  • JavaScript/TypeScript
from hopx_ai import Sandbox
import os

API_KEY = os.getenv("HOPX_API_KEY")

with Sandbox.create(template="code-interpreter", api_key=API_KEY) as sandbox:
    # Simple command
    result = sandbox.commands.run("echo 'Hello from bash!'")
    print(f"Output: {result.stdout.strip()}")
    print(f"Exit code: {result.exit_code}")
    
    # List files
    result = sandbox.commands.run("ls -lah /workspace")
    print(f"/workspace contents:\n{result.stdout}")
    
    # Check Python version
    result = sandbox.commands.run("python --version")
    print(f"Python version: {result.stdout.strip()}")

Commands with Environment Variables

Pass environment variables to commands:
  • Python
  • JavaScript/TypeScript
# Use environment variables in command
result = sandbox.commands.run(
    'echo "API Key: $API_KEY, Region: $AWS_REGION"',
    env={
        "API_KEY": "sk-test-123",
        "AWS_REGION": "us-west-2"
    }
)

print(f"Output: {result.stdout.strip()}")

# Run Python with custom PYTHONPATH
result = sandbox.commands.run(
    "python -c 'import sys; print(sys.path)'",
    env={"PYTHONPATH": "/workspace/custom:/workspace/lib"}
)

print(f"Python path:\n{result.stdout}")

Custom Working Directory

Execute commands in a specific directory:
  • Python
  • JavaScript/TypeScript
# Create a directory
sandbox.files.mkdir("/workspace/myproject")
sandbox.files.write("/workspace/myproject/file.txt", "Hello!")

# Run command in that directory
result = sandbox.commands.run(
    "pwd && ls -la",
    working_dir="/workspace/myproject"
)

print(f"Output:\n{result.stdout}")

# Verify working directory
result = sandbox.commands.run(
    "cat file.txt",  # No path needed, we're in the dir
    working_dir="/workspace/myproject"
)

print(f"File content: {result.stdout.strip()}")

Piped Commands

Execute complex commands with pipes:
  • Python
  • JavaScript/TypeScript
# Create test file
sandbox.files.write("/workspace/data.txt", "apple\nbanana\napple\norange\napple\n")

# Use pipes
result = sandbox.commands.run(
    "cat /workspace/data.txt | sort | uniq -c"
)

print(f"Word count:\n{result.stdout}")

# More complex pipeline
result = sandbox.commands.run(
    "ps aux | grep python | wc -l"
)

print(f"Python processes: {result.stdout.strip()}")

Installing Packages

Install packages and use them:
  • Python
  • JavaScript/TypeScript
# Install Python package
result = sandbox.commands.run("pip install requests")
print("Package installed")

# Use the package
result = sandbox.run_code("""
import requests
response = requests.get('https://api.github.com')
print(f"Status: {response.status_code}")
""")

print(result.stdout)

# Install multiple packages
result = sandbox.commands.run("pip install pandas numpy matplotlib")
print("Multiple packages installed")

Git Operations

Clone repositories and work with Git:
  • Python
  • JavaScript/TypeScript
# Clone a repository
result = sandbox.commands.run(
    "git clone https://github.com/example/repo.git /workspace/repo",
    timeout=60
)

print("Repository cloned")

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

print(f"Git status:\n{result.stdout}")

# List files in repository
result = sandbox.commands.run("ls -la /workspace/repo")
print(f"Repository files:\n{result.stdout}")

Command Timeouts

Handle long-running commands with timeouts:
  • Python
  • JavaScript/TypeScript
# Command with timeout
try:
    result = sandbox.commands.run(
        "sleep 100",  # This will timeout
        timeout=5
    )
except Exception as e:
    print(f"Command timed out: {e}")

# Long-running command that should complete
result = sandbox.commands.run(
    "sleep 2 && echo 'Done!'",
    timeout=10
)

print(f"Output: {result.stdout.strip()}")

Background Code Execution

Run code in the background:
  • Python
  • JavaScript/TypeScript
# Start background execution
result = sandbox.run_code_background(
    """
import time
from http.server import HTTPServer, SimpleHTTPRequestHandler
server = HTTPServer(('0.0.0.0', 8000), SimpleHTTPRequestHandler)
server.serve_forever()
    """,
    language="python"
)

process_id = result['process_id']
print(f"Background process started: {process_id}")

# Do other work
import time
time.sleep(2)

# Check if server is running
result = sandbox.commands.run("curl -s http://localhost:8000 | head -n 5")
print(f"Server response:\n{result.stdout}")

# Stop the background process
sandbox.kill_process(process_id)
print("Background process stopped")
For shell commands, use language="bash" with run_code_background(). The commands resource is for synchronous command execution only.

Next Steps