概述
在沙箱中执行终端命令,就像在真实的 Linux 终端中一样。
基本用法
import { Sandbox } from '@e2b/code-interpreter'
async function main() {
const sandbox = await Sandbox.create()
const result = await sandbox.commands.run('ls -l')
console.log(result)
await sandbox.kill()
}
main()
流式输出
SDK 允许在命令执行期间实时流式获取输出,通过回调函数实时接收标准输出和错误输出。
import { Sandbox } from '@e2b/code-interpreter'
async function main() {
const sandbox = await Sandbox.create()
const result = await sandbox.commands.run('echo hello; sleep 1; echo world', {
onStdout: (data) => {
console.log(data)
},
onStderr: (data) => {
console.log(data)
},
})
console.log(result)
await sandbox.kill()
}
main()
后台运行命令
在沙箱中后台运行命令,允许您异步执行长时间任务而不阻塞主程序。
import { Sandbox } from '@e2b/code-interpreter'
async function main() {
const sandbox = await Sandbox.create()
// Start the command in the background
const command = await sandbox.commands.run('echo hello; sleep 10; echo world', {
background: true,
onStdout: (data) => {
console.log(data)
},
})
// Kill the command
await command.kill()
await sandbox.kill()
}
main()
文档反馈
(如有产品使用问题,请 提交工单)