Skip to main content

What You’ll Learn

  • Running shell commands for system info
  • Running Python one-liners and multi-line scripts
  • Writing scripts to the sandbox filesystem and executing them
  • Using shell pipelines (sort, uniq, etc.)
  • All within a single sandbox session
  • Proper cleanup with try/finally and sbx.kill()

Prerequisites

This example is available in Python. TypeScript version coming soon.

Code Walkthrough

Shell commands — run any system utility directly:
from declaw import Sandbox

sbx = Sandbox.create(template="python", timeout=300)
try:
    result = sbx.commands.run("uname -a")
    print(f"  {result.stdout.strip()}")
Python one-liner — invoke python3 -c for quick computations:
    result = sbx.commands.run(
        'python3 -c "import sys; print(\'Python \' + sys.version.split()[0]); print(\'2+2 =\', 2+2)"'
    )
    print(f"  {result.stdout.strip()}")
Write and execute a Python script — use sbx.files.write() to upload code, then run it:
    script = """
def fibonacci(n):
    a, b = 0, 1
    result = []
    for _ in range(n):
        result.append(a)
        a, b = b, a + b
    return result

fib = fibonacci(10)
print("First 10 Fibonacci numbers:", fib)
print("Sum:", sum(fib))
"""
    sbx.files.write("/tmp/fib.py", script)
    result = sbx.commands.run("python3 /tmp/fib.py")
    print(f"  {result.stdout.strip()}")
Shell pipeline — chain Unix utilities:
    result = sbx.commands.run(
        "printf 'banana\\napple\\ncherry\\ndate\\napple' | sort | uniq -c | sort -rn"
    )
    print(f"  Output:\n{result.stdout}")
Shell script — write a .sh file and run it with sh:
    shell_script = """#!/bin/sh
echo "=== System Report ==="
echo "Kernel: $(uname -r)"
echo "Architecture: $(uname -m)"
echo "CPU cores: $(nproc)"
echo "Memory: $(cat /proc/meminfo | head -1)"
echo "Python: $(python3 --version)"
"""
    sbx.files.write("/tmp/report.sh", shell_script)
    result = sbx.commands.run("sh /tmp/report.sh")
    print(f"  {result.stdout.strip()}")
finally:
    sbx.kill()

Expected Output

==================================================
Declaw Multi-Language Execution Example
==================================================

--- 1. Shell: System Info ---
  Linux declaw-sandbox 6.1.158 ...

--- 2. Python: Version & Calculation ---
  Python 3.10.12
  2+2 = 4

--- 3. Python Script: Fibonacci ---
  First 10 Fibonacci numbers: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
  Sum: 88

--- 4. Shell: Pipeline ---
  2 apple
  1 date
  ...

--- 5. Shell Script: System Report ---
  Kernel: 6.1.158
  Architecture: x86_64
  ...