How to upload files to E2B sandbox
Quick answer
Use the
e2b_code_interpreter package's Sandbox class to upload files by calling sandbox.files.write(filename, data). Initialize the sandbox with your API key from os.environ and then write file bytes to the sandbox filesystem.PREREQUISITES
Python 3.8+E2B API key set in environment variable <code>E2B_API_KEY</code>pip install e2b-code-interpreter
Setup
Install the e2b-code-interpreter Python package and set your E2B API key as an environment variable before running the code.
- Install package:
pip install e2b-code-interpreter - Set environment variable:
export E2B_API_KEY='your_api_key_here'(Linux/macOS) orset E2B_API_KEY=your_api_key_here(Windows)
pip install e2b-code-interpreter output
Collecting e2b-code-interpreter Downloading e2b_code_interpreter-1.0.0-py3-none-any.whl (15 kB) Installing collected packages: e2b-code-interpreter Successfully installed e2b-code-interpreter-1.0.0
Step by step
This example shows how to initialize the Sandbox, upload a local file to the sandbox filesystem, and verify the upload by reading the file back.
import os
from e2b_code_interpreter import Sandbox
# Initialize sandbox with API key from environment
sandbox = Sandbox(api_key=os.environ["E2B_API_KEY"])
# Read local file bytes
with open("example.txt", "rb") as f:
file_data = f.read()
# Upload file to sandbox filesystem
sandbox.files.write("example.txt", file_data)
# Verify upload by reading file back
uploaded_data = sandbox.files.read("example.txt")
print("Uploaded file content:\n", uploaded_data.decode())
# Close sandbox session
sandbox.close() output
Uploaded file content: This is a sample file for E2B sandbox upload.
Common variations
You can upload multiple files by repeating sandbox.files.write() calls. For large files, read and write in chunks. The sandbox supports running code after upload for processing files.
Async usage is not currently supported by the e2b_code_interpreter SDK.
Troubleshooting
- If you get an authentication error, verify your
E2B_API_KEYenvironment variable is set correctly. - If file upload fails, check the file path and ensure the file is readable.
- Call
sandbox.close()to cleanly close the session and release resources.
Key Takeaways
- Use
sandbox.files.write(filename, data)to upload files to the E2B sandbox. - Always initialize
Sandboxwith your API key fromos.environ. - Close the sandbox session with
sandbox.close()to free resources. - Read local files in binary mode before uploading.
- Check environment variables and file paths if uploads fail.