更新时间:2026-09-07 GMT+08:00
分享

文件操作

AgentSphere沙箱实例提供了独立的文件系统,您可以通过SDK进行文件读写、目录管理、文件查询等操作。

前提条件

以下示例均基于E2B SDK,请确保已完成配置本地E2B SDK执行环境。

文件操作

写入和读取文件

您可以使用files.write方法向沙箱实例写入文件,使用files.read方法读取文件内容。支持写入文本和JSON等格式的数据。

from e2b import Sandbox

# template字段的值为已有的template_id
sandbox = Sandbox.create(template="<template_id>")

# 设置沙箱实例的traffic_access_token,可选,如果已经安装前提条件中的patch文件则无需此设置
sandbox.connection_config._ConnectionConfig__extra_sandbox_headers["E2b-Traffic-Access-Token"] = sandbox.traffic_access_token

# 写入文本文件
sandbox.files.write("/tmp/test.txt", "Hello AgentSphere!")

# 读取文件内容
content = sandbox.files.read("/tmp/test.txt")
print(content)  # 输出: Hello AgentSphere!

# 写入JSON文件
import json
sandbox.files.write("/tmp/data.json", json.dumps({"key": "value", "count": 42}))

# 读取并解析JSON
raw = sandbox.files.read("/tmp/data.json")
parsed = json.loads(raw)
print(parsed)  # 输出: {'key': 'value', 'count': 42}

检查文件是否存在

您可以使用files.exists方法检查沙箱实例中指定路径的文件是否存在,返回布尔值。

from e2b import Sandbox

sandbox = Sandbox.create(template="<template_id>")

# 设置沙箱实例的traffic_access_token,可选,如果已经安装前提条件中的patch文件则无需此设置
sandbox.connection_config._ConnectionConfig__extra_sandbox_headers["E2b-Traffic-Access-Token"] = sandbox.traffic_access_token

# 写入文件后检查
sandbox.files.write("/tmp/check.txt", "exists!")
print(sandbox.files.exists("/tmp/check.txt"))  # 输出: True

# 检查不存在的文件
print(sandbox.files.exists("/tmp/nonexistent.txt"))  # 输出: False

创建目录

您可以使用files.make_dir方法在沙箱实例中创建目录,支持递归创建多级目录。

from e2b import Sandbox

sandbox = Sandbox.create(template="<template_id>")

# 设置沙箱实例的traffic_access_token,可选,如果已经安装前提条件中的patch文件则无需此设置
sandbox.connection_config._ConnectionConfig__extra_sandbox_headers["E2b-Traffic-Access-Token"] = sandbox.traffic_access_token

# 递归创建多级目录
sandbox.files.make_dir("/tmp/nested/deep/dir")
print(sandbox.files.exists("/tmp/nested/deep/dir"))  # 输出: True

列出目录内容

您可以使用files.list方法列出指定目录下的文件和子目录,返回文件信息列表。

from e2b import Sandbox

sandbox = Sandbox.create(template="<template_id>")

# 设置沙箱实例的traffic_access_token,可选,如果已经安装前提条件中的patch文件则无需此设置
sandbox.connection_config._ConnectionConfig__extra_sandbox_headers["E2b-Traffic-Access-Token"] = sandbox.traffic_access_token

# 创建目录并写入文件
sandbox.files.make_dir("/tmp/list_test")
sandbox.files.write("/tmp/list_test/a.txt", "aaa")
sandbox.files.write("/tmp/list_test/b.txt", "bbb")

# 列出目录内容
items = sandbox.files.list("/tmp/list_test")
for item in items:
    print(f"文件名: {item.name}")
# 输出:
# 文件名: a.txt
# 文件名: b.txt

重命名文件或目录

您可以使用files.rename方法重命名沙箱实例中的文件或目录。

from e2b import Sandbox

sandbox = Sandbox.create(template="<template_id>")

# 设置沙箱实例的traffic_access_token,可选,如果已经安装前提条件中的patch文件则无需此设置
sandbox.connection_config._ConnectionConfig__extra_sandbox_headers["E2b-Traffic-Access-Token"] = sandbox.traffic_access_token

# 写入文件后重命名
sandbox.files.write("/tmp/src.txt", "rename me")
sandbox.files.rename("/tmp/src.txt", "/tmp/dst.txt")
print(sandbox.files.exists("/tmp/dst.txt"))  # 输出: True
print(sandbox.files.exists("/tmp/src.txt"))  # 输出: False

删除文件

您可以使用files.remove方法删除沙箱实例中的指定文件。

from e2b import Sandbox

sandbox = Sandbox.create(template="<template_id>")

# 设置沙箱实例的traffic_access_token,可选,如果已经安装前提条件中的patch文件则无需此设置
sandbox.connection_config._ConnectionConfig__extra_sandbox_headers["E2b-Traffic-Access-Token"] = sandbox.traffic_access_token

# 写入文件后删除
sandbox.files.write("/tmp/remove_me.txt", "delete me")
sandbox.files.remove("/tmp/remove_me.txt")
print(sandbox.files.exists("/tmp/remove_me.txt"))  # 输出: False

删除目录

删除目录操作为递归删除,将同时删除目录下的所有子目录和文件,且不可恢复。

您可以使用files.remove方法递归删除目录及其下的所有内容。

from e2b import Sandbox

sandbox = Sandbox.create(template="<template_id>")

# 设置沙箱实例的traffic_access_token,可选,如果已经安装前提条件中的patch文件则无需此设置
sandbox.connection_config._ConnectionConfig__extra_sandbox_headers["E2b-Traffic-Access-Token"] = sandbox.traffic_access_token

# 创建目录和文件
sandbox.files.make_dir("/tmp/rmdir/sub")
sandbox.files.write("/tmp/rmdir/sub/file.txt", "data")

# 递归删除目录
sandbox.files.remove("/tmp/rmdir")
print(sandbox.files.exists("/tmp/rmdir"))  # 输出: False

查看文件属性

您可以使用files.get_info方法获取文件的大小、修改时间等属性信息。

from e2b import Sandbox

sandbox = Sandbox.create(template="<template_id>")

# 设置沙箱实例的traffic_access_token,可选,如果已经安装前提条件中的patch文件则无需此设置
sandbox.connection_config._ConnectionConfig__extra_sandbox_headers["E2b-Traffic-Access-Token"] = sandbox.traffic_access_token

# 写入文件后获取属性
sandbox.files.write("/tmp/info.txt", "info test")
info = sandbox.files.get_info("/tmp/info.txt")
print(info)

生成上传/下载的url链接

您可以使用upload_url/download_url生成临时访问链接,可以在浏览器或外部工具中直接上传或下载文件。

from e2b import Sandbox

sandbox = Sandbox.create(template="<template_id>")

# 上传文件
url = sandbox.upload_url("/tmp/e2b_upload_test.txt")
assert url is not None and url != ""
print(f"[PASS] upload_url: {url}")

# 下载文件
sandbox.files.write("/tmp/e2b_download_test.txt", "download me")
url = sandbox.download_url("/tmp/e2b_download_test.txt")
assert url is not None and url != ""
print(f"[PASS] download_url: {url}")

sandbox.kill()

文件上传/下载/解压缩

您需要以执行命令的方式进行解压缩文件。

import time
from e2b_code_interpreter import Sandbox
from e2b.sandbox.filesystem.filesystem import WriteEntry

sbx = Sandbox.create(
    template="<template_id>",
    validate_api_key=False,
    timeout=300,
)
time.sleep(5)

# 批量写入文件
sbx.files.write_files([
    WriteEntry(path="/home/user/multi_a.txt", data="file A content"),
    WriteEntry(path="/home/user/multi_b.txt", data="file B content"),
])
logger.info("write_files (batch upload) OK")

# 读取批量写入的文件
a_content = sbx.files.read("/home/user/multi_a.txt", format="text")
assert a_content == "file A content"
logger.info("batch upload read back OK")

# 流式读取文件
sbx.files.write("/home/user/download_me.txt", "download this file")
stream = sbx.files.read("/home/user/download_me.txt", format="stream")
downloaded = b"".join(stream)
assert b"download this file" in downloaded
logger.info("stream download OK")

# 压缩文件
sbx.commands.run("cd /home/user && echo 'compress test' > file1.txt && echo 'more data' > file2.txt")
sbx.commands.run("cd /home/user && zip archive.zip file1.txt file2.txt")
assert sbx.files.exists("/home/user/archive.zip") is True
logger.info("zip compress OK")

# 解压文件
sbx.commands.run("cd /home/user && mkdir -p extracted && unzip archive.zip -d extracted")
f1 = sbx.files.read("/home/user/extracted/file1.txt", format="text")
assert "compress test" in f1
logger.info("unzip extract OK")

# 清理文件
sbx.commands.run("rm -rf /home/user/multi_a.txt /home/user/multi_b.txt /home/user/download_me.txt /home/user/file1.txt /home/user/file2.txt /home/user/archive.zip /home/user/extracted")

sbx.kill()

完整代码示例

以下示例基于已创建的Sandbox对象。

import os
import json
from e2b import Sandbox


sandbox = Sandbox.create(template="<template_id>")

# 设置沙箱实例的traffic_access_token,可选,如果已经安装前提条件中的patch文件则无需此设置
sandbox.connection_config._ConnectionConfig__extra_sandbox_headers["E2b-Traffic-Access-Token"] = sandbox.traffic_access_token

# 读写文本文件
def test_write_and_read_text(sandbox):
    sandbox.files.write("/tmp/e2b_test.txt", "Hello E2B Filesystem!")
    content = sandbox.files.read("/tmp/e2b_test.txt")
    assert "Hello E2B Filesystem!" in content
    print(f"[PASS] write & read text: {content.strip()}")

# 读写JSON文件
def test_write_json(sandbox):
    payload = {"key": "value", "count": 42}
    sandbox.files.write("/tmp/e2b_data.json", json.dumps(payload))
    raw = sandbox.files.read("/tmp/e2b_data.json")
    parsed = json.loads(raw)
    assert parsed["key"] == "value"
    assert parsed["count"] == 42
    print(f"[PASS] write & read JSON: {parsed}")

# 检查文件是否存在
def test_exists(sandbox):
    sandbox.files.write("/tmp/e2b_exists_check.txt", "exists!")
    assert sandbox.files.exists("/tmp/e2b_exists_check.txt") is True
    assert sandbox.files.exists("/tmp/nonexistent_file_abc123.txt") is False
    print("[PASS] exists check: True/False correct")

# 递归创建多级目录
def test_make_dir(sandbox):
    sandbox.files.make_dir("/tmp/e2b_nested/deep/dir")
    assert sandbox.files.exists("/tmp/e2b_nested/deep/dir") is True
    print("[PASS] make_dir nested")

# 列出目录下的文件和子目录
def test_list(sandbox):
    sandbox.files.make_dir("/tmp/e2b_list_test")
    sandbox.files.write("/tmp/e2b_list_test/a.txt", "aaa")
    sandbox.files.write("/tmp/e2b_list_test/b.txt", "bbb")
    items = sandbox.files.list("/tmp/e2b_list_test")
    names = [item.name for item in items]
    assert "a.txt" in names
    assert "b.txt" in names
    print(f"[PASS] list directory: {names}")

# 重命名文件或目录
def test_rename(sandbox):
    sandbox.files.write("/tmp/e2b_rename_src.txt", "rename me")
    sandbox.files.rename("/tmp/e2b_rename_src.txt", "/tmp/e2b_rename_dst.txt")
    assert sandbox.files.exists("/tmp/e2b_rename_dst.txt") is True
    assert sandbox.files.exists("/tmp/e2b_rename_src.txt") is False
    print("[PASS] rename file")

# 删除指定文件
def test_remove(sandbox):
    sandbox.files.write("/tmp/e2b_remove_me.txt", "delete me")
    sandbox.files.remove("/tmp/e2b_remove_me.txt")
    assert sandbox.files.exists("/tmp/e2b_remove_me.txt") is False
    print("[PASS] remove file")

# 递归删除目录及其下所有内容
def test_remove_directory(sandbox):
    sandbox.files.make_dir("/tmp/e2b_rmdir/sub")
    sandbox.files.write("/tmp/e2b_rmdir/sub/file.txt", "data")
    sandbox.files.remove("/tmp/e2b_rmdir")
    assert sandbox.files.exists("/tmp/e2b_rmdir") is False
    print("[PASS] remove directory (recursive)")

# 获取文件的大小、修改时间等属性
def test_get_info(sandbox):
    sandbox.files.write("/tmp/e2b_info.txt", "info test")
    try:
        info = sandbox.files.get_info("/tmp/e2b_info.txt")
        assert info is not None
        print(f"[PASS] get_info: {info}")
    except AttributeError:
        info = sandbox.files.get_info("/tmp/e2b_info.txt")
        print(f"[PASS] get_info (alternate): {info}")

相关文档

  • 创建沙箱模板:了解如何创建自定义沙箱模板,预装所需的运行环境和依赖包。
  • 创建API Key:了解如何创建和管理API Key,获取访问凭据。
  • 创建网关实例:了解Agent网关的配置和管理,获取数据面访问地址。
  • E2B SDK官方文档:了解E2B SDK的完整接口说明和更多用法示例。
  • 如果在使用SDK时遇到连接失败、认证错误等问题,请先检查环境变量配置是否正确,特别是E2B_API_URL、E2B_SANDBOX_URL和E2B_API_KEY是否与控制台中的信息一致。

相关文档