Execute commands
This guide shows you how to execute commands in the sandbox, handle output, and manage errors effectively.
The SDK provides two methods for command execution:
exec()
- Run a command and wait for complete result. Best for most use cases.execStream()
- Stream output in real-time. Best for long-running commands where you need immediate feedback.
Use exec()
for simple commands that complete quickly:
import { getSandbox } from "@cloudflare/sandbox";
const sandbox = getSandbox(env.Sandbox, "my-sandbox");
// Execute a single commandconst result = await sandbox.exec("python --version");
console.log(result.stdout); // "Python 3.11.0"console.log(result.exitCode); // 0console.log(result.success); // true
import { getSandbox } from '@cloudflare/sandbox';
const sandbox = getSandbox(env.Sandbox, 'my-sandbox');
// Execute a single commandconst result = await sandbox.exec('python --version');
console.log(result.stdout); // "Python 3.11.0"console.log(result.exitCode); // 0console.log(result.success); // true
When passing user input or dynamic values, avoid string interpolation to prevent injection attacks:
// Unsafe - vulnerable to injectionconst filename = userInput;await sandbox.exec(`cat ${filename}`);
// Safe - use proper escaping or validationconst safeFilename = filename.replace(/[^a-zA-Z0-9_.-]/g, "");await sandbox.exec(`cat ${safeFilename}`);
// Better - write to file and executeawait sandbox.writeFile("/tmp/input.txt", userInput);await sandbox.exec("python process.py /tmp/input.txt");
// Unsafe - vulnerable to injectionconst filename = userInput;await sandbox.exec(`cat ${filename}`);
// Safe - use proper escaping or validationconst safeFilename = filename.replace(/[^a-zA-Z0-9_.-]/g, '');await sandbox.exec(`cat ${safeFilename}`);
// Better - write to file and executeawait sandbox.writeFile('/tmp/input.txt', userInput);await sandbox.exec('python process.py /tmp/input.txt');
Commands can fail in two ways:
- Non-zero exit code - Command ran but failed (result.success === false)
- Execution error - Command couldn't start (throws exception)
try { const result = await sandbox.exec("python analyze.py");
if (!result.success) { // Command failed (non-zero exit code) console.error("Analysis failed:", result.stderr); console.log("Exit code:", result.exitCode);
// Handle specific exit codes if (result.exitCode === 1) { throw new Error("Invalid input data"); } else if (result.exitCode === 2) { throw new Error("Missing dependencies"); } }
// Success - process output return JSON.parse(result.stdout);} catch (error) { // Execution error (couldn't start command) console.error("Execution failed:", error.message); throw error;}
try { const result = await sandbox.exec('python analyze.py');
if (!result.success) { // Command failed (non-zero exit code) console.error('Analysis failed:', result.stderr); console.log('Exit code:', result.exitCode);
// Handle specific exit codes if (result.exitCode === 1) { throw new Error('Invalid input data'); } else if (result.exitCode === 2) { throw new Error('Missing dependencies'); } }
// Success - process output return JSON.parse(result.stdout);
} catch (error) { // Execution error (couldn't start command) console.error('Execution failed:', error.message); throw error;}
The sandbox supports shell features like pipes, redirects, and chaining:
// Pipes and filtersconst result = await sandbox.exec('ls -la | grep ".py" | wc -l');console.log("Python files:", result.stdout.trim());
// Output redirectionawait sandbox.exec("python generate.py > output.txt 2> errors.txt");
// Multiple commandsawait sandbox.exec("cd /workspace && npm install && npm test");
// Pipes and filtersconst result = await sandbox.exec('ls -la | grep ".py" | wc -l');console.log('Python files:', result.stdout.trim());
// Output redirectionawait sandbox.exec('python generate.py > output.txt 2> errors.txt');
// Multiple commandsawait sandbox.exec('cd /workspace && npm install && npm test');
// Run inline Pythonconst result = await sandbox.exec('python -c "print(sum([1, 2, 3, 4, 5]))"');console.log("Sum:", result.stdout.trim()); // "15"
// Run a script fileawait sandbox.writeFile( "/workspace/analyze.py", `import sysprint(f"Argument: {sys.argv[1]}")`,);
await sandbox.exec("python /workspace/analyze.py data.csv");
// Run inline Pythonconst result = await sandbox.exec('python -c "print(sum([1, 2, 3, 4, 5]))"');console.log('Sum:', result.stdout.trim()); // "15"
// Run a script fileawait sandbox.writeFile('/workspace/analyze.py', `import sysprint(f"Argument: {sys.argv[1]}")`);
await sandbox.exec('python /workspace/analyze.py data.csv');
- Check exit codes - Always verify
result.success
andresult.exitCode
- Validate inputs - Escape or validate user input to prevent injection
- Use streaming - For long operations, use
execStream()
for real-time feedback - Handle errors - Check stderr for error details
Verify the command exists in the container:
const check = await sandbox.exec("which python3");if (!check.success) { console.error("python3 not found");}
const check = await sandbox.exec('which python3');if (!check.success) { console.error('python3 not found');}
Use absolute paths or change directory:
// Use absolute pathawait sandbox.exec("python /workspace/my-app/script.py");
// Or change directoryawait sandbox.exec("cd /workspace/my-app && python script.py");
// Use absolute pathawait sandbox.exec('python /workspace/my-app/script.py');
// Or change directoryawait sandbox.exec('cd /workspace/my-app && python script.py');
- Commands API reference - Complete method documentation
- Background processes guide - Managing long-running processes
- Streaming output guide - Advanced streaming patterns
- Code Interpreter guide - Higher-level code execution
Was this helpful?
- Resources
- API
- New to Cloudflare?
- Directory
- Sponsorships
- Open Source
- Support
- Help Center
- System Status
- Compliance
- GDPR
- Company
- cloudflare.com
- Our team
- Careers
- © 2025 Cloudflare, Inc.
- Privacy Policy
- Terms of Use
- Report Security Issues
- Trademark
-