Skip to main content
Use sandbox.commands to execute shell commands in your sandbox. Commands can run in the foreground (blocking) or background (non-blocking), with real-time streaming of stdout and stderr.

Quick Reference

OperationMethod
Run commandsandbox.commands.run(cmd)
Background commandsandbox.commands.run(cmd, background=True)
List processessandbox.commands.list()
Kill processsandbox.commands.kill(pid)
Send stdinsandbox.commands.send_stdin(pid, data)
Interactive PTYsandbox.pty.create()

Basic Usage

from moru import Sandbox

sandbox = Sandbox.create()

# Run a simple command
result = sandbox.commands.run("echo 'Hello, World!'")
print(result.stdout)  # Hello, World!
print(result.exit_code)  # 0

# Run with error
result = sandbox.commands.run("ls /nonexistent")
print(result.stderr)  # ls: cannot access...
print(result.exit_code)  # 2

sandbox.kill()

Command Result

The CommandResult object contains:
PropertyTypeDescription
stdoutstringStandard output
stderrstringStandard error
exit_code / exitCodenumberExit code (0 = success)
errorstring?Error message if command failed to execute

Execution Modes

Foreground (Default)

Command runs and blocks until completion:
# Blocks until command finishes
result = sandbox.commands.run("sleep 5 && echo done")
print(result.stdout)  # done (after 5 seconds)

Background

Command runs without blocking:
# Returns immediately
handle = sandbox.commands.run("python3 server.py", background=True)

# Do other work...

# Later, check on the command
result = handle.wait()  # Now block until done

Streaming Output

Receive stdout/stderr in real-time:
def on_output(data):
    print(f"Output: {data}", end="")

result = sandbox.commands.run(
    "for i in 1 2 3; do echo $i; sleep 1; done",
    on_stdout=on_output,
    on_stderr=lambda data: print(f"Error: {data}", end=""),
    timeout=30
)

Environment Variables

Set environment variables for a command:
result = sandbox.commands.run(
    "echo $MY_VAR",
    envs={"MY_VAR": "Hello"}
)
print(result.stdout)  # Hello

Working Directory

Specify the working directory:
result = sandbox.commands.run("pwd", cwd="/tmp")
print(result.stdout)  # /tmp

User Context

Run commands as a different user:
# Run as root
result = sandbox.commands.run("whoami", user="root")
print(result.stdout)  # root

# Run as specific user
result = sandbox.commands.run("whoami", user="alice")

Timeouts

Set command timeout:
from moru.exceptions import TimeoutException

try:
    # Command timeout (how long the command can run)
    result = sandbox.commands.run("sleep 60", timeout=5)
except TimeoutException:
    print("Command timed out after 5 seconds")

Next Steps