E2B Sandbox SDK Usage#
Price: 0.000056 PTC/second, no charges during sandbox paused stateDownload SDK: It is recommended to use the following tested and more compatible version:
pip install e2b==1.2.0b5
pip install e2b-code-interpreter==1.2.0b5
Configuration#
api_key = "" # 302.ai API key
domain="sandbox.302.ai"
You can also configure via .env
file:E2B_API_KEY=sk_*** # Your API key
E2B_DOMAIN=sandbox.302.ai # 302.ai sandbox service address
Usage#
1. Import SDK#
from e2b_code_interpreter import Sandbox,
2. Create a sandbox#
sdx = Sandbox(api_key=api_key, timeout=60, domain=domain)
sdx_id = sdx.sandbox_id
3. List sandboxes#
sdx_list = Sandbox.list(api_key=api_key, domain=domain)
print(sdx_list.next_items())
4. Reset sandbox lifetime#
Maximum lifetime is 3600 seconds. For example, reset to 300 seconds:5. Get sandbox configuration#
metrics = sdx.get_metrics()
6. Check if sandbox is running#
7. Pause sandbox#
8. Resume sandbox#
sdx = Sandbox.resume(sdx_id, api_key=api_key, domain=domain)
9. Run code#
sdx.run_code("print('hello world')")
10. List files in sandbox#
sdx.files.list(path="/home/user")
11. Write file to sandbox#
with open(r"your_file_path", "rb") as f:
file = f.read()
sdx.files.write("/home/user/test.txt", file, "root")
12. Download file from sandbox#
def download_sandbox_file(file, save_path):
# Export a file from sandbox to local
# :param file: File path in sandbox
# :param save_path: Local save directory
def check_e2b_file_type(file_name):
# Determine if sandbox file is text or binary
mime_type, _ = mimetypes.guess_type(file_name)
if mime_type is None:
mode = 'wb'
encoding = None
else:
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)
f.write(content)
13. Kill sandbox (irreversible)#
Modified at 2025-09-22 03:18:08