Skip to main content

What You’ll Learn

  • Running a basic shell command with sbx.commands.run()
  • Passing environment variables via the envs parameter
  • Setting the working directory via the cwd parameter
  • Handling failing commands by inspecting exit_code and stderr
  • Running multi-line / chained commands with &&
  • Proper cleanup with try/finally and sbx.kill()

Prerequisites

Code Walkthrough

Basic commandresult.stdout contains the captured output:
result = sbx.commands.run('echo "Hello World"')
print(f"stdout: {result.stdout}")
print(f"exit_code: {result.exit_code}")
Environment variables — pass a dict via envs:
result = sbx.commands.run(
    "echo $GREETING",
    envs={"GREETING": "Hi from Declaw"},
)
print(f"stdout: {result.stdout}")
Working directory — set with cwd:
result = sbx.commands.run("pwd", cwd="/tmp")
# stdout: /tmp
Failing commands — non-zero exit codes do not raise exceptions by default:
result = sbx.commands.run("exit 42")
print(f"exit_code: {result.exit_code}")   # 42
print(f"stderr: {result.stderr!r}")
if result.exit_code != 0:
    print(f"Command failed as expected with exit code {result.exit_code}")
Chained commands — use shell operators:
result = sbx.commands.run('echo "line1" && echo "line2" && echo "line3"')
print(f"stdout:\n{result.stdout}")

Expected Output

==================================================
Declaw Run Command Example
==================================================

--- Creating Sandbox ---
Sandbox created: sbx_abc123

--- 1. Basic Command ---
stdout: Hello World
exit_code: 0

--- 2. Command with Environment Variables ---
stdout: Hi from Declaw
exit_code: 0

--- 3. Command with Working Directory ---
stdout: /tmp
exit_code: 0

--- 4. Failing Command ---
exit_code: 42
stderr: ''
Command failed as expected with exit code 42

--- 5. Multi-line Command ---
stdout:
line1
line2
line3
exit_code: 0

--- Cleaning Up ---
Sandbox killed.

==================================================
Done!
==================================================