全栈应用服务器

  • 全栈应用服务器 > 使用指南 > 沙箱服务概述 > 运行你的第一个沙箱

    运行你的第一个沙箱

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

    概述

    本快速入门指南演示如何启动沙箱环境、在其中执行代码以及管理文件。

    第 1 步:账户设置

    如果您还没有七牛账户,请访问 七牛云注册页面 创建账户。

    第 2 步:API 配置

    七牛云 API 密钥管理 获取你的认证密钥,并将其添加到 .env 文件中:

    E2B_API_KEY=sk_***
    E2B_API_URL=https://<RegionID>-sandbox.qiniuapi.com
    

    注: 七牛沙箱服务完全兼容 E2B 的 API, 您可以直接使用 E2B SDK。使用七牛服务时需要同时配置 E2B_API_KEYE2B_API_URL 两个环境变量,其中 <RegionID> 为您的区域标识符。

    当前支持的区域有 cn-yangzhou-1

    E2B_API_KEY=sk_***
    E2B_API_URL=https://cn-yangzhou-1-sandbox.qiniuapi.com
    

    第 3 步:SDK 安装

    为你的编程语言安装相应的包:

    JavaScript/TypeScript:

    npm i @e2b/code-interpreter dotenv
    

    Python:

    pip install e2b-code-interpreter python-dotenv
    

    第 4 步:实现代码

    JavaScript/TypeScript (index.ts):

    // index.ts
    import 'dotenv/config'
    import { Sandbox } from '@e2b/code-interpreter'
    
    async function main() {
      const sbx = await Sandbox.create() // By default the sandbox is alive for 5 minutes
      const execution = await sbx.runCode('print("hello world")') // Execute Python inside the sandbox
      console.log(execution.logs)
    
      const files = await sbx.files.list('/')
      console.log(files)
    
      await sbx.kill()
    }
    
    main()
    

    Python (main.py):

    # main.py
    from dotenv import load_dotenv
    load_dotenv()
    from e2b_code_interpreter import Sandbox
    
    sbx = Sandbox() # By default the sandbox is alive for 5 minutes
    execution = sbx.run_code("print('hello world')") # Execute Python inside the sandbox
    print(execution.logs)
    
    files = sbx.files.list("/")
    print(files)
    
    sbx.kill()
    

    第 5 步:执行命令

    JavaScript/TypeScript:

    npx tsx ./index.ts
    

    Python:

    python main.py
    

    注意事项

    默认情况下,沙箱的存活时间为 5 分钟。

    以上内容是否对您有帮助?