Skip to main content
Use sandbox.commands.run() to execute shell commands. This is the primary method for running commands in your sandbox.

Basic Execution

from moru import Sandbox

sandbox = Sandbox.create()

# Simple command
result = sandbox.commands.run("echo 'Hello'")
print(result.stdout)  # Hello

# Complex command with pipes
result = sandbox.commands.run("cat /etc/passwd | grep root | cut -d: -f1")
print(result.stdout)  # root

# Multi-line script
result = sandbox.commands.run("""
for i in 1 2 3; do
    echo "Number: $i"
done
""")

sandbox.kill()

Options Reference

OptionTypeDefaultDescription
backgroundbooleanfalseRun without blocking
envsobject{}Environment variables
userstring"user"User to run as
cwdstring/home/userWorking directory
timeout / timeoutMsnumber60s / 60000msCommand timeout
on_stdout / onStdoutfunction-Stdout callback
on_stderr / onStderrfunction-Stderr callback
stdinbooleanfalseKeep stdin open
request_timeout / requestTimeoutMsnumber-API request timeout

Environment Variables

# Set environment variables for the command
result = sandbox.commands.run(
    "python3 -c 'import os; print(os.environ.get(\"API_KEY\"))'",
    envs={
        "API_KEY": "secret_123",
        "DEBUG": "true",
        "PATH": "/usr/local/bin:/usr/bin:/bin"
    }
)

Working Directory

# Create and work in a directory
sandbox.files.make_dir("/home/user/project")
sandbox.files.write("/home/user/project/script.py", "print('Hello')")

result = sandbox.commands.run("python3 script.py", cwd="/home/user/project")
print(result.stdout)  # Hello

User Context

# Run as root for privileged operations
result = sandbox.commands.run("apt-get update", user="root")

# Check which user is running
result = sandbox.commands.run("whoami")
print(result.stdout)  # user

result = sandbox.commands.run("whoami", user="root")
print(result.stdout)  # root

Timeouts

from moru.exceptions import TimeoutException

# Command will be killed after 5 seconds
try:
    result = sandbox.commands.run("sleep 60", timeout=5)
except TimeoutException:
    print("Command timed out")

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

Streaming Output

Receive output in real-time as the command runs:
import sys

def handle_stdout(data):
    sys.stdout.write(data)
    sys.stdout.flush()

def handle_stderr(data):
    sys.stderr.write(data)
    sys.stderr.flush()

# Stream output in real-time
result = sandbox.commands.run(
    "for i in $(seq 1 10); do echo $i; sleep 0.5; done",
    on_stdout=handle_stdout,
    on_stderr=handle_stderr,
    timeout=30
)

# Final result still contains all output
print(f"\nTotal output: {len(result.stdout)} chars")

Exit Code Handling

from moru.exceptions import CommandExitException

# Check exit code manually
result = sandbox.commands.run("grep pattern /nonexistent/file")
if result.exit_code != 0:
    print(f"Command failed with exit code {result.exit_code}")
    print(f"Error: {result.stderr}")

# Or use exception handling with specific commands
try:
    # This will raise if exit code is non-zero
    result = sandbox.commands.run("false")  # Always exits with 1
except CommandExitException as e:
    print(f"Exit code: {e.exit_code}")

Complex Scripts

# Run a complex shell script
script = """
#!/bin/bash
set -e

echo "Setting up environment..."
cd /home/user

# Create virtual environment
python3 -m venv venv
source venv/bin/activate

# Install dependencies
pip install requests pandas

echo "Environment ready!"
"""

result = sandbox.commands.run(script, timeout=120)
print(result.stdout)

Error Handling

from moru.exceptions import TimeoutException, SandboxException

try:
    result = sandbox.commands.run("some_command", timeout=30)
    if result.exit_code != 0:
        print(f"Command failed: {result.stderr}")
except TimeoutException:
    print("Command timed out")
except SandboxException as e:
    print(f"Sandbox error: {e}")

Next Steps