E2B for coding assistants
Quick answer
Use the
e2b_code_interpreter Python package to run secure code execution sandboxes for coding assistants. Initialize a Sandbox with your API key, run code snippets safely, and manage files within the sandbox environment.PREREQUISITES
Python 3.8+E2B API keypip install e2b-code-interpreter
Setup
Install the e2b-code-interpreter package and set your E2B API key as an environment variable for secure authentication.
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
Initialize the sandbox, run Python code securely, and retrieve the output. This example runs a simple Python print statement.
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 code snippet
execution = sandbox.run_code("print('Hello from E2B sandbox')")
# Print output
print(execution.text)
# Close sandbox when done
sandbox.close() output
Hello from E2B sandbox
Common variations
You can upload files to the sandbox, install packages dynamically, and run multi-line scripts. The sandbox supports Python code execution with isolated environment management.
import os
from e2b_code_interpreter import Sandbox
sandbox = Sandbox(api_key=os.environ["E2B_API_KEY"])
# Write a file to sandbox
sandbox.files.write("data.csv", b"id,value\n1,100\n2,200")
# Install a package
sandbox.run_code("import subprocess; subprocess.run(['pip','install','pandas'])")
# Run multi-line code using triple quotes
code = '''
import pandas as pd
df = pd.read_csv('data.csv')
print(df.describe())
'''
execution = sandbox.run_code(code)
print(execution.text)
sandbox.close() output
id value count 2.0 2.000000 mean 1.5 150.000000 std 0.7 70.710678 min 1.0 100.000000 25% 1.25 125.000000 50% 1.5 150.000000 75% 1.75 175.000000 max 2.0 200.000000
Troubleshooting
- If you see authentication errors, verify your
E2B_API_KEYenvironment variable is set correctly. - For package installation failures, ensure the sandbox has internet access or preinstall required packages.
- If code execution hangs, check for infinite loops or resource limits in your code.
Key Takeaways
- Use
Sandboxfrome2b_code_interpreterto run secure isolated Python code for coding assistants. - Manage files and install packages dynamically inside the sandbox environment.
- Always close the sandbox after use to free resources and maintain security.