跳转到内容
搜索文档

执行命令

最后更新 查看 MarkdownAgent 设置

本指南说明如何在沙箱中执行命令、处理输出并有效管理错误。

选择正确的方法

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');

处理错误

命令可能以两种方式失败:

  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;
}

执行 shell 命令

沙箱支持管道、重定向与链式等 shell 功能:

// 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');

超时

为命令设置最大执行时间,防止长时间运行的操作无限阻塞。

单命令超时

在选项中传入 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. 单命令 timeout(在 exec() 上,最高优先级)
  2. 会话级 commandTimeoutMs(在 createSession() 上)
  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');

相关资源

这篇文档对您有帮助吗?