How to run code in E2B sandbox
Quick answer
Use the
e2b-code-interpreter Python package to run code securely in the E2B sandbox. Instantiate Sandbox with your API key, then call run_code() with your code string to execute it safely in an isolated 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.
- Run
pip install e2b-code-interpreterto install the SDK. - Set your API key in the environment:
export E2B_API_KEY='your_api_key'(Linux/macOS) orset E2B_API_KEY=your_api_key(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
Use the Sandbox class to run Python code securely. The example below runs a simple print statement and outputs the result.
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 in sandbox
code = "print('Hello from E2B sandbox')"
execution = sandbox.run_code(code)
# Print output
print("Sandbox output:", execution.text)
# Close sandbox session
sandbox.close() output
Sandbox output: Hello from E2B sandbox
Common variations
You can upload files to the sandbox environment and run code that uses them. Use sandbox.files.write(filename, data) to add files. You can also run shell commands or install packages inside the sandbox by running code that calls subprocess.
import os
from e2b_code_interpreter import Sandbox
sandbox = Sandbox(api_key=os.environ["E2B_API_KEY"])
# Upload a CSV file
csv_data = "name,age\nAlice,30\nBob,25"
sandbox.files.write("data.csv", csv_data.encode())
# Run code that reads the file
code = '''
import pandas as pd
df = pd.read_csv('data.csv')
print(df)
'''
# Install pandas inside sandbox
sandbox.run_code("import subprocess; subprocess.run(['pip','install','pandas'])")
result = sandbox.run_code(code)
print("DataFrame output:\n", result.text)
sandbox.close() output
DataFrame output:
name age
0 Alice 30
1 Bob 25
Troubleshooting
- If you get authentication errors, verify your
E2B_API_KEYenvironment variable is set correctly. - If code execution hangs or fails, ensure your code is valid Python and does not require unsupported system calls.
- Use
sandbox.close()to clean up resources after running code to avoid session leaks.
Key Takeaways
- Use the
e2b-code-interpreterpackage andSandboxclass to run code securely. - Always set your API key in the
E2B_API_KEYenvironment variable before running code. - Upload files with
sandbox.files.write()to use data inside the sandbox. - Close the sandbox session with
sandbox.close()to free resources.