| 20 | } |
| 21 | |
| 22 | async function runExample() { |
| 23 | console.log("Creating E2B Code Interpreter instance..."); |
| 24 | |
| 25 | // Create a new Code Interpreter instance |
| 26 | const sandbox = await CodeInterpreter.create({ apiKey }); |
| 27 | |
| 28 | try { |
| 29 | // Example 1: Execute a simple Python code |
| 30 | console.log("\n--- Example 1: Execute Python Code ---"); |
| 31 | const pythonResult = await sandbox.notebook.execCell(` |
| 32 | import sys |
| 33 | print(f"Python version: {sys.version}") |
| 34 | print("Hello from E2B!") |
| 35 | 2 + 2 |
| 36 | `); |
| 37 | |
| 38 | console.log("Output:", pythonResult.text); |
| 39 | console.log("Results:", pythonResult.results); |
| 40 | |
| 41 | // Example 2: Write and read a file |
| 42 | console.log("\n--- Example 2: File Operations ---"); |
| 43 | await sandbox.filesystem.write("/tmp/example.txt", "Hello, E2B file system!"); |
| 44 | const fileContent = await sandbox.filesystem.read("/tmp/example.txt"); |
| 45 | console.log("File content:", fileContent); |
| 46 | |
| 47 | // List files in a directory |
| 48 | const files = await sandbox.filesystem.list("/tmp"); |
| 49 | console.log("Files in /tmp:", files); |
| 50 | |
| 51 | // Example 3: Install and use a package |
| 52 | console.log("\n--- Example 3: Install and Use Package ---"); |
| 53 | const installResult = await sandbox.notebook.execCell("!pip install numpy"); |
| 54 | console.log("Install output:", installResult.text); |
| 55 | |
| 56 | const numpyResult = await sandbox.notebook.execCell(` |
| 57 | import numpy as np |
| 58 | arr = np.array([1, 2, 3, 4, 5]) |
| 59 | print(f"NumPy array: {arr}") |
| 60 | print(f"Mean: {np.mean(arr)}") |
| 61 | `); |
| 62 | |
| 63 | console.log("NumPy output:", numpyResult.text); |
| 64 | |
| 65 | } catch (error: unknown) { |
| 66 | console.error("Error:", error instanceof Error ? error.message : String(error)); |
| 67 | } finally { |
| 68 | // Always close the interpreter to free resources |
| 69 | await sandbox.close(); |
| 70 | console.log("\nInterpreter closed."); |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | // Run the example |
| 75 | runExample(); |