"""02 E2B SANDBOX. Run untrusted code inside a real cloud sandbox using the e2b SDK. Same task as 01_docker_sandbox.py, but e2b manages the machine for you. No Docker needed on your laptop. Run: python 02_e2b_sandbox.py "print('hello from e2b')" Needs: pip install e2b-code-interpreter, and E2B_API_KEY set in your environment (get a free key at e2b.dev). Without a key, this script tells you what it WOULD do and exits 0. It never fakes output. """ import os import sys CODE = sys.argv[1] if len(sys.argv) > 1 else "print('hello from the sandbox')\nprint(2 + 2)" def main(): api_key = os.environ.get("E2B_API_KEY") if not api_key: print("E2B_API_KEY is not set. Here is what this script would do with a key:") print(" 1. Start a fresh e2b sandbox (a real cloud VM, not your machine).") print(f" 2. Run this code inside it:\n {CODE!r}") print(" 3. Print stdout/stderr captured from inside the sandbox.") print(" 4. Kill the sandbox. Nothing survives the run.") print("Set E2B_API_KEY (free at e2b.dev) and re-run this script to see it live.") sys.exit(0) try: from e2b_code_interpreter import Sandbox except ImportError: print("e2b-code-interpreter is not installed. Run: pip install e2b-code-interpreter") sys.exit(0) print("Starting a throwaway e2b sandbox...") # e2b SDK v2+ uses Sandbox.create(); v1 used Sandbox(). Support both. sbx = Sandbox.create() if hasattr(Sandbox, "create") else Sandbox() try: print(f"Running:\n{CODE}\n") execution = sbx.run_code(CODE) for line in execution.logs.stdout: print(f"stdout: {line}") for line in execution.logs.stderr: print(f"stderr: {line}") if execution.error: print(f"error: {execution.error.name}: {execution.error.value}") finally: sbx.kill() print("Sandbox killed. Nothing left behind.") if __name__ == "__main__": main()