概述
SDK 允许您使用 Sandbox.connect() 重新连接到活动的沙箱实例,这对于在不活动期后重用沙箱非常有用。
步骤 1:检索沙箱 ID
首先,通过使用 Sandbox.list() 列出正在运行的沙箱来获取 ID。
import { Sandbox } from '@e2b/code-interpreter'
async function main() {
const sbx = await Sandbox.create()
const paginator = await Sandbox.list({
query: { state: ['running'] },
})
const runningSandboxes = await paginator.nextItems()
if (runningSandboxes.length === 0) {
throw new Error('No running sandboxes found')
}
const sandboxId = runningSandboxes[0].sandboxId
console.log('Sandbox ID:', sandboxId)
}
main()
步骤 2:连接到沙箱
获得 ID 后,建立连接并恢复操作。
import { Sandbox } from '@e2b/code-interpreter'
async function main() {
const sandboxId = 'your-sandbox-id' // 使用步骤 1 获取的 ID
const sandbox = await Sandbox.connect(sandboxId)
const result = await sandbox.commands.run("whoami")
console.log(`Running in sandbox ${sandbox.sandboxId} as "${result.stdout.trim()}"`)
await sandbox.kill()
}
main()
文档反馈
(如有产品使用问题,请 提交工单)