Skip to content

非公式本サイトは非公式の日本語ドキュメントであり、Cloudflare 公式サイトではありません。最新情報はdevelopers.cloudflare.comをご確認ください。

コマンドを実行する

最終更新 Markdown で表示Agent セットアップ

このガイドでは、サンドボックスでコマンドを実行し、出力を扱い、エラーを効果的に処理する方法を説明します。

適切なメソッドを選ぶ

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); // true
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);  // 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 通りで失敗します。

  1. ゼロ以外の終了コード - コマンドは動いたが失敗した(result.success === false
  2. 実行エラー - コマンドを起動できなかった(例外を投げる)
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');

Python スクリプトを実行する

// 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 command
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 command

グローバルタイムアウト

環境変数 COMMAND_TIMEOUT_MS を設定すると、すべてのセッションのすべての exec() にグローバルなデフォルトタイムアウトを定義できます。

タイムアウトの優先順位

複数のタイムアウトがある場合、いちばん具体的な値が優先されます。

  1. コマンド単位exec()timeout(最優先)
  2. セッション単位createSession()commandTimeoutMs
  3. グローバル の環境変数 COMMAND_TIMEOUT_MS(優先度がいちばん低い)

どれも設定していない場合、コマンドはタイムアウトなしで動きます。

タイムアウトはプロセスを停止しません

ベストプラクティス

  • 終了コードを確認する - 常に result.successresult.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');

関連情報

役に立ちましたか?