FEATURED · 精选文章

CubeSandbox Python SDK完全指南:pip install后10个必会API

发布时间 / 2026/9/15 14:55:42
来源 / 创域科博编辑部
栏目 / 资讯中心
CubeSandbox Python SDK完全指南:pip install后10个必会API CubeSandbox Python SDK完全指南pip install后10个必会API【免费下载链接】CubeSandboxInstant, Concurrent, Secure Lightweight Sandbox for AI Agents.项目地址: https://gitcode.com/GitHub_Trending/cu/CubeSandboxCubeSandbox 是一个为 AI Agent 打造的即时、并发、安全且轻量级的代码沙箱平台其官方CubeSandbox Python SDKPyPI 包名cubesandbox让 Python 开发者用几行代码就能创建 MicroVM 沙箱、执行代码、管理文件与快照。本文面向新手带你用pip install完成安装后掌握 10 个最常用的 API。一、CubeSandbox 是什么为什么选它简单来说CubeSandbox 是AI Agent 的安全执行环境。它基于 MicroVM 隔离技术每个沙箱都有独立的内核、文件系统和网络沙箱创建耗时通常在 50ms 级别且支持内存级快照——暂停后恢复连运行中的变量都不用重新初始化。官方 Python SDK 的设计目标是Pythonic、兼容 E2B 生态、开箱即用。核心模块位于 sdk/python/cubesandbox/sandbox.py接口文档见 sdk/python/README.md。二、一键安装与环境配置30秒完成pip install cubesandboxSDK 要求 Python 3.9依赖只有httpx和requests见 pyproject.toml。然后通过环境变量告诉 SDK 三件事连接谁API 地址、用哪个模板、代理节点在哪export CUBE_API_URLhttp://your-cubeapi-host:3000 export CUBE_TEMPLATE_IDyour-template-id export CUBE_PROXY_NODE_IPyour-cubeproxy-node-ip # 远程访问时需要环境变量必填作用CUBE_API_URL✅CubeAPI 管理面地址默认http://127.0.0.1:3000CUBE_TEMPLATE_ID✅创建沙箱用的模板 IDCUBE_PROXY_NODE_IP远程绕过*.cube.appDNS 直连代理节点CUBE_API_KEY可选开启鉴权的部署需要也支持直接传Config对象sdk/python/cubesandbox/_config.py适合多集群场景。三、10个必会API详解1️⃣Sandbox.create()— 秒级启动一个沙箱一切从这里开始。它封装了POST /sandboxes50ms 内即可得到一个运行中的 MicroVMfrom cubesandbox import Sandbox with Sandbox.create() as sb: # with 块结束自动销毁 result sb.run_code(1 1) print(result.text) # 2常用参数template模板 ID不传则读CUBE_TEMPLATE_IDtimeout空闲超时秒数env_vars注入沙箱的环境变量别名envs兼容 E2Bdistribution_scope把沙箱钉到指定计算节点如[node-a]lifecycle{on_timeout: pause, auto_resume: True}可实现空闲自动暂停 透明恢复详见 auto-resume.py2️⃣sb.run_code()— 在沙箱里执行代码这是 AI Agent 场景最核心的 API它流式返回执行结果result sb.run_code(x 42\nx * 2) print(result.text) # 84最终表达式值 result sb.run_code(print(hello)) print(result.logs.stdout) # [hello\n]亮点特性变量持久同一个沙箱内多次run_code共享命名空间sb.run_code(x 100)之后sb.run_code(x 1)得到101实时回调on_stdout/on_stderr/on_error可逐行流式打印输出结果对象Execution含.text、.logs、.error、.results定义在 sdk/python/cubesandbox/_models.pysb.run_code(for i in range(3): print(i), on_stdoutlambda msg: print(out:, msg.text))3️⃣sb.commands.run()— 执行 Shell 命令不只是 Python沙箱里可以直接跑任意 Shell 命令result sb.commands.run(echo hello cube) print(result.stdout) # hello cube\n返回CommandResultstdout/stderr/exit_code三件套支持timeout、cwd、envs参数。实现见 sdk/python/cubesandbox/_commands.py示例见 cmd.py。4️⃣sb.files— 文件读写全家桶通过files属性可以像操作本地文件一样操作沙箱文件系统sb.files.write(/tmp/hello.txt, Hello, world!) print(sb.files.read(/tmp/hello.txt)) # Hello, world! sb.files.make_dir(/tmp/mydir) entries sb.files.list(/tmp) # 目录列表 info sb.files.stat(/tmp/hello.txt) # 元信息 print(sb.files.exists(/tmp/hello.txt)) # True sb.files.rename(/tmp/hello.txt, /tmp/new.txt) sb.files.remove(/tmp/new.txt)还有高阶玩法write_files([(path, data), ...])批量写入支持 byteswatch_dir(path)实时监听目录变更事件见 sdk/python/cubesandbox/_filesystem.py5️⃣sb.pause()Sandbox.connect()— 内存快照暂停与秒级恢复这是 CubeSandbox 的招牌能力暂停沙箱时内存状态被完整快照恢复后连运行中的程序都原地复活sb Sandbox.create() sb.pause() # 等待快照完成默认轮询30s sb.pause(waitFalse) # 不等待异步执行 sb2 Sandbox.connect(sb.sandbox_id) # connect 会自动恢复暂停的沙箱pause还支持timeout60, interval0.5自定义轮询。完整示例见 pause.py。6️⃣Volume— 持久化卷数据跨沙箱存活沙箱会销毁但数据不该跟着没了。Volume提供 e2b 兼容的持久卷管理from cubesandbox import Sandbox, Volume, VolumeMount vol Volume.create(my-data) # 创建卷 # vol Volume.create(my-data, drivercos) # 指定插件 with Sandbox.create(volume_mounts{/workspace: vol}) as sb: sb.files.write(/workspace/note.txt, persisted!)同一个卷可以挂到多个沙箱支持VolumeMount(vol, read_onlyTrue)按挂载点设置只读Volume.list()/get_info()/connect()/destroy()覆盖完整生命周期完整 API 与错误码见 docs/volume.md 和 sdk/python/cubesandbox/_volume.py7️⃣network— 三层网络策略断网、白名单、L7 注入AI Agent 沙箱最需要安全围栏。network参数支持 L3/L4 黑白名单 L7 精细规则# 彻底断网 sb Sandbox.create(allow_internet_accessFalse) # 出口白名单只允许访问指定网段 sb Sandbox.create(network{allow_out: [172.67.0.0/16]})L7 层可以按 host/path/SNI 匹配支持审计日志和凭据注入用Rule/Match/Action/Inject四个 dataclass 定义见 sdk/python/cubesandbox/_policy.pyfrom cubesandbox import Rule, Match, Action, Inject rules [Rule( namellm_api, matchMatch(hostapi.example.com, path/v1/chat, sniapi.example.com), actionAction(allowTrue, auditmetadata, inject[Inject(headerAuthorization, formatBearer ${SECRET}, secretsk_xxx)]), )] sb Sandbox.create(network{allow_out: [api.example.com], rules: rules})更多场景黑名单、限制公网访问等可参考 network_denylist.py 与 restrict_public_access.py。8️⃣sb.get_info()/Sandbox.list()— 沙箱状态巡检info sb.get_info() print(info.sandbox_id, info.state) # 类型化属性datetime、SandboxState 枚举 print(info[sandboxID]) # 也支持原始 dict 访问 print(Sandbox.list()) # 所有运行中的沙箱 print(Sandbox.list_v2()) # v2 接口支持服务端过滤 print(Sandbox.health()) # {status: ok, sandboxes: 4}SandboxInfo提供cpu_count、memory_mb、disk_size_mb、end_at等字段既能属性访问也能 JSON 序列化方便接入监控面板。9️⃣ 快照三部曲create_snapshot()/rollback()/clone()0.3.0 之后CubeSandbox 把快照玩出了花——把时间机器做成了三个 API# 打快照沙箱销毁后快照依然有效 snap sb.create_snapshot(namev1) # 回滚文件系统内存回到快照那一刻 sb.rollback(snap.snapshot_id) # 克隆一键从当前状态派生 n 个新沙箱支持并发 clones sb.clone(n4, concurrency4)clone是 RL 训练、多路探索场景的利器内部自动处理快照创建、并发拉起和失败回滚部分失败会自动清理孤儿沙箱。实现细节见 sandbox.py。 上下文管理器与sb.kill()— 优雅的生命周期收尾with Sandbox.create() as sb: ... # with 块退出 → 自动 kill 释放连接sb.kill()手动销毁沙箱DELETE /sandboxes/:idsb.set_timeout(600)动态调整空闲 TTL传NEVER_TIMEOUT即 -1 可关闭空闲超时sb.get_host(port)拿到沙箱端点的虚拟域名{port}-{id}.cube.app把沙箱里的 Web 服务直接暴露给浏览器异常体系清晰SandboxNotFoundError、TemplateNotFoundError、ApiError等sdk/python/cubesandbox/_exceptions.py四、常见问题新手必看现象原因与解决Template not found模板 ID 错误检查CUBE_TEMPLATE_IDConnection refusedCubeAPI 不可达确认CUBE_API_URL端口 3000 通SSL: CERTIFICATE_VERIFY_FAILED自建 CA 场景设置SSL_CERT_FILE指向根证书远程访问域名解析失败设置CUBE_PROXY_NODE_IP启用 IP 直连绕过 DNS更多示例脚本自动暂停/自动销毁、环境变量注入等都在 examples/code-sandbox-quickstart/ 目录下配套中文教程见 README_zh.md。五、写在最后回顾一下这 10 个必会 API 的地图Sandbox.create()创建 → 2.run_code()执行代码 → 3.commands.run()跑 Shell → 4.files文件操作 → 5.pause()/connect()快照恢复 → 6.Volume持久化 → 7.network安全围栏 → 8.get_info()/list()巡检 → 9. 快照/回滚/克隆 → 10. 上下文管理器优雅收尾从pip install cubesandbox到给 AI Agent 搭一个用完即焚、秒级恢复的安全执行环境你只需要一个下午。快去试试吧 【免费下载链接】CubeSandboxInstant, Concurrent, Secure Lightweight Sandbox for AI Agents.项目地址: https://gitcode.com/GitHub_Trending/cu/CubeSandbox创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
RELATED — 相关阅读

相关资讯

LATEST — 最新资讯

最新发布

TODAY — 本日精选

新闻

WEEKLY — 本周精选

新闻

MONTHLY — 本月精选

新闻