下载SDK 建议使用下面这个版本,已经经过测试兼容性比较好
pip install e2b==1.2.0b5
pip install e2b-code-interpreter==1.2.0b5
api_key = "" #302.ai的apikey
domain="sandbox.302.ai"E2B_API_KEY=sk_*** # 你的Apikey
E2B_DOMAIN=sandbox.302.ai # 指向 302.ai 沙箱服务地址from e2b_code_interpreter import Sandbox,sdx = Sandbox(api_key=api_key, timeout=60, domain=domain)
sdx_id = sdx.sandbox_idsdx_list = Sandbox.list(api_key=api_key, domain=domain)
print(sdx_list.next_items())sdx.set_timeout(30)metrics = sdx.get_metrics()sdx.is_running()sdx.pause()sdx = Sandbox.resume(sdx_id, api_key=api_key, domain=domain)sdx.run_code("print('hello world')")sdx.files.list(path="/home/user")with open(r"你的文件路径", "rb") as f:
file = f.read()
sdx.files.write("/home/user/test.txt", file, "root")def download_sandbox_file(file, save_path):
"""
导出沙盒里的文件到本地
:param file: 沙盒里的文件路径
:param save_path: 本地保存的文件夹路径
:return:
"""
def check_e2b_file_type(file_name):
"""
判断e2b的文件是文本还是二进制
Args:
file_name:
Returns:
"""
# Write file to local filesystem
mime_type, _ = mimetypes.guess_type(file_name)
# 判断MIME类型是否为None
if mime_type is None:
# 如果无法判断MIME类型,则使用二进制写入模式
mode = 'wb'
encoding = None
else:
# 根据MIME类型判断是否为文本文件
if 'text' in mime_type:
mode = 'w'
encoding = 'utf-8'
else:
mode = 'wb'
encoding = None
return mode, encoding
mode, encoding = check_e2b_file_type(os.path.basename(file))
target_path = os.path.join(save_path, file)
# 确保目标文件的目录存在
os.makedirs(os.path.dirname(target_path), exist_ok=True)
with open(target_path, mode, encoding=encoding) as f:
f_format = "text" if encoding else "bytes"
content = sdx.files.read(file, format=f_format) # sdx是之前初始化的沙盒对象
f.write(content)sdx.kill()