How to install E2B SDK
Quick answer
Install the
e2b-code-interpreter Python package using pip install e2b-code-interpreter. Then import Sandbox from e2b_code_interpreter to securely run code in a sandboxed environment.PREREQUISITES
Python 3.8+pip installedE2B API key (set as environment variable E2B_API_KEY)
Setup
Install the official E2B SDK Python package e2b-code-interpreter via pip. Set your E2B API key as an environment variable E2B_API_KEY before running your code.
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
Use the Sandbox class from e2b_code_interpreter to run Python code securely. Initialize the sandbox with your API key from environment variables, run code, and retrieve output.
import os
from e2b_code_interpreter import Sandbox
# Initialize sandbox with API key from environment
sandbox = Sandbox(api_key=os.environ["E2B_API_KEY"])
# Run Python code securely
execution = sandbox.run_code("print('Hello from sandbox')")
# Print the output
print(execution.text)
# Close the sandbox session
sandbox.close() output
Hello from sandbox
Common variations
You can upload files to the sandbox using sandbox.files.write(filename, data) and install packages dynamically by running pip commands inside the sandbox. The SDK currently supports synchronous usage; async support is not available.
import os
from e2b_code_interpreter import Sandbox
sandbox = Sandbox(api_key=os.environ["E2B_API_KEY"])
# Upload a CSV file to sandbox
with open("local.csv", "rb") as f:
sandbox.files.write("data.csv", f.read())
# Install pandas inside sandbox
sandbox.run_code("import subprocess; subprocess.run(['pip', 'install', 'pandas'])")
# Run code that uses pandas
result = sandbox.run_code("import pandas as pd\ndf = pd.read_csv('data.csv')\nprint(df.head())")
print(result.text)
sandbox.close() output
col1 col2 0 1 2 1 3 4 2 5 6
Troubleshooting
- If you see
ModuleNotFoundError, ensure you installede2b-code-interpreterin the correct Python environment. - If
E2B_API_KEYis missing or invalid, set it correctly in your environment before running your script. - For network or authentication errors, verify your internet connection and API key validity.
Key Takeaways
- Install the E2B SDK with
pip install e2b-code-interpreterand set your API key inE2B_API_KEYenvironment variable. - Use
Sandboxfrome2b_code_interpreterto securely run Python code and manage files inside the sandbox. - You can dynamically install packages and upload files to the sandbox for complex code execution.
- Always close the sandbox session with
sandbox.close()to free resources. - Check environment and API key setup if you encounter module or authentication errors.