このガイドでは、サンドボックスでコマンドを実行し、出力を扱い、エラーを効果的に処理する方法を説明します。
SDK には、コマンドを実行する複数の方法があります。
exec()- コマンドを実行し、完了結果を待ちます。ビルド、インストール、スクリプトなど、一度きりのコマンドに適しています。execStream()- 出力をリアルタイムでストリームします。すぐフィードバックが必要な長時間コマンドに適しています。startProcess()- バックグラウンドプロセスを起動します。動き続けてほしい Web サーバー、データベース、サービスに適しています。
すぐに完了する単純なコマンドには exec() を使います。
import { getSandbox } from "@cloudflare/sandbox";
const sandbox = getSandbox(env.Sandbox, "my-sandbox");
// Execute a single command
const result = await sandbox.exec("python --version");
console.log(result.stdout); // "Python 3.11.0"
console.log(result.exitCode); // 0
console.log(result.success); // trueimport { getSandbox } from '@cloudflare/sandbox';
const sandbox = getSandbox(env.Sandbox, 'my-sandbox');
// Execute a single command
const result = await sandbox.exec('python --version');
console.log(result.stdout); // "Python 3.11.0"
console.log(result.exitCode); // 0
console.log(result.success); // trueユーザー入力や動的な値を渡すときは、インジェクション攻撃を防ぐため文字列補間を避けます。
// Unsafe - vulnerable to injection
const filename = userInput;
await sandbox.exec(`cat ${filename}`);
// Safe - use proper escaping or validation
const safeFilename = filename.replace(/[^a-zA-Z0-9_.-]/g, "");
await sandbox.exec(`cat ${safeFilename}`);
// Better - write to file and execute
await sandbox.writeFile("/tmp/input.txt", userInput);
await sandbox.exec("python process.py /tmp/input.txt");// Unsafe - vulnerable to injection
const filename = userInput;
await sandbox.exec(`cat ${filename}`);
// Safe - use proper escaping or validation
const safeFilename = filename.replace(/[^a-zA-Z0-9_.-]/g, '');
await sandbox.exec(`cat ${safeFilename}`);
// Better - write to file and execute
await sandbox.writeFile('/tmp/input.txt', userInput);
await sandbox.exec('python process.py /tmp/input.txt');コマンドは次の 2 通りで失敗します。
- ゼロ以外の終了コード - コマンドは動いたが失敗した(
result.success === false) - 実行エラー - コマンドを起動できなかった(例外を投げる)
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;
}サンドボックスは、パイプ、リダイレクト、チェインなどのシェル機能をサポートします。
// Pipes and filters
const result = await sandbox.exec('ls -la | grep ".py" | wc -l');
console.log("Python files:", result.stdout.trim());
// Output redirection
await sandbox.exec("python generate.py > output.txt 2> errors.txt");
// Multiple commands
await sandbox.exec("cd /workspace && npm install && npm test");// Pipes and filters
const result = await sandbox.exec('ls -la | grep ".py" | wc -l');
console.log('Python files:', result.stdout.trim());
// Output redirection
await sandbox.exec('python generate.py > output.txt 2> errors.txt');
// Multiple commands
await sandbox.exec('cd /workspace && npm install && npm test');// Run inline Python
const result = await sandbox.exec('python -c "print(sum([1, 2, 3, 4, 5]))"');
console.log("Sum:", result.stdout.trim()); // "15"
// Run a script file
await sandbox.writeFile(
"/workspace/analyze.py",
`
import sys
print(f"Argument: {sys.argv[1]}")
`,
);
await sandbox.exec("python /workspace/analyze.py data.csv");// Run inline Python
const result = await sandbox.exec('python -c "print(sum([1, 2, 3, 4, 5]))"');
console.log('Sum:', result.stdout.trim()); // "15"
// Run a script file
await sandbox.writeFile('/workspace/analyze.py', `
import sys
print(f"Argument: {sys.argv[1]}")
`);
await sandbox.exec('python /workspace/analyze.py data.csv');長時間処理が無限にブロックしないよう、コマンドの最大実行時間を設定します。
1 つのコマンドにタイムアウトを付けるには、オプションの timeout を渡します。
const result = await sandbox.exec("npm run build", {
timeout: 30000, // 30 seconds
});const result = await sandbox.exec('npm run build', {
timeout: 30000 // 30 seconds
});セッション内の全コマンドのデフォルトタイムアウトは、commandTimeoutMs で設定します。
const session = await sandbox.createSession({
commandTimeoutMs: 10000, // 10s default for all commands
});
await session.exec("npm install"); // Times out after 10s
await session.exec("npm run build"); // Times out after 10s
// Per-command timeout overrides the session default
await session.exec("npm test", { timeout: 60000 }); // 60s for this commandconst session = await sandbox.createSession({
commandTimeoutMs: 10000 // 10s default for all commands
});
await session.exec('npm install'); // Times out after 10s
await session.exec('npm run build'); // Times out after 10s
// Per-command timeout overrides the session default
await session.exec('npm test', { timeout: 60000 }); // 60s for this command環境変数 COMMAND_TIMEOUT_MS を設定すると、すべてのセッションのすべての exec() にグローバルなデフォルトタイムアウトを定義できます。
複数のタイムアウトがある場合、いちばん具体的な値が優先されます。
- コマンド単位 の
exec()のtimeout(最優先) - セッション単位 の
createSession()のcommandTimeoutMs - グローバル の環境変数
COMMAND_TIMEOUT_MS(優先度がいちばん低い)
どれも設定していない場合、コマンドはタイムアウトなしで動きます。
- 終了コードを確認する - 常に
result.successとresult.exitCodeを確認します - 入力を検証する - インジェクションを防ぐため、ユーザー入力をエスケープまたは検証します
- ストリーミングを使う - 長時間の処理では、リアルタイムのフィードバックに
execStream()を使います - バックグラウンドプロセスを使う - 動き続けてほしいサービス(Web サーバー、データベース)には、このガイドではなく バックグラウンドプロセスガイド を使います
- エラーを処理する - エラーの詳細は stderr を確認します
コンテナ内にそのコマンドがあるか確認します。
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 path
await sandbox.exec("python /workspace/my-app/script.py");
// Or change directory
await sandbox.exec("cd /workspace/my-app && python script.py");// Use absolute path
await sandbox.exec('python /workspace/my-app/script.py');
// Or change directory
await sandbox.exec('cd /workspace/my-app && python script.py');- Commands API リファレンス - メソッドの完全なドキュメント
- バックグラウンドプロセスガイド - 長時間動くプロセスの管理
- 出力のストリーミングガイド - 高度なストリーミングのパターン
- コードインタープリターガイド - より高水準なコード実行