()
| 12 | |
| 13 | // Example of starting and interacting with a Python REPL session |
| 14 | async function pythonREPLExample() { |
| 15 | console.log('Starting a Python REPL session...'); |
| 16 | |
| 17 | // Start Python interpreter in interactive mode |
| 18 | const result = await executeCommand({ |
| 19 | command: 'python -i', |
| 20 | timeout_ms: 10000 |
| 21 | }); |
| 22 | |
| 23 | // Extract PID from the result text |
| 24 | const pidMatch = result.content[0].text.match(/Command started with PID (\d+)/); |
| 25 | const pid = pidMatch ? parseInt(pidMatch[1]) : null; |
| 26 | |
| 27 | if (!pid) { |
| 28 | console.error("Failed to get PID from Python process"); |
| 29 | return; |
| 30 | } |
| 31 | |
| 32 | console.log(`Started Python session with PID: ${pid}`); |
| 33 | |
| 34 | // Initial read to get the Python prompt with timeout |
| 35 | console.log("Reading initial output..."); |
| 36 | const initialOutput = await readOutput({ |
| 37 | pid, |
| 38 | timeout_ms: 2000 |
| 39 | }); |
| 40 | console.log("Initial Python prompt:", initialOutput.content[0].text); |
| 41 | |
| 42 | // Send a simple Python command with wait_for_prompt |
| 43 | console.log("Sending simple command..."); |
| 44 | const simpleResult = await sendInput({ |
| 45 | pid, |
| 46 | input: 'print("Hello from Python!")\n', |
| 47 | wait_for_prompt: true, |
| 48 | timeout_ms: 3000 |
| 49 | }); |
| 50 | console.log('Python output with wait_for_prompt:', simpleResult.content[0].text); |
| 51 | |
| 52 | // Send a multi-line code block with wait_for_prompt |
| 53 | console.log("Sending multi-line code..."); |
| 54 | const multilineCode = ` |
| 55 | def greet(name): |
| 56 | return f"Hello, {name}!" |
| 57 | |
| 58 | for i in range(3): |
| 59 | print(greet(f"Guest {i+1}")) |
| 60 | `; |
| 61 | |
| 62 | const multilineResult = await sendInput({ |
| 63 | pid, |
| 64 | input: multilineCode + '\n', |
| 65 | wait_for_prompt: true, |
| 66 | timeout_ms: 5000 |
| 67 | }); |
| 68 | console.log('Python multi-line output with wait_for_prompt:', multilineResult.content[0].text); |
| 69 | |
| 70 | // Terminate the session |
| 71 | await forceTerminate({ pid }); |
no test coverage detected