全栈应用服务器

  • 全栈应用服务器 > 使用指南 > 沙箱服务概述 > 在沙箱中执行命令

    在沙箱中执行命令

    最近更新时间: 2026-02-12 11:22:02

    概述

    在沙箱中执行终端命令,就像在真实的 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()
    
    以上内容是否对您有帮助?