From 15a4445dc15e406ae9ad6fa12800555a031dc504 Mon Sep 17 00:00:00 2001 From: Meet Patel Date: Sat, 12 Oct 2024 10:42:19 +0530 Subject: [PATCH] Displays correct output - added proper logic to display output + with error handling - converted a div -> text-area for proper output --- learn.html | 2 +- script.js | 32 +++++++++++++++++++++++++++++--- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/learn.html b/learn.html index c94a234..a5fa146 100644 --- a/learn.html +++ b/learn.html @@ -52,7 +52,7 @@

Python Lessons

-
+
diff --git a/script.js b/script.js index 0b48b9e..9cc8686 100644 --- a/script.js +++ b/script.js @@ -64,17 +64,43 @@ print(greet("Alice"))`, 1); } async function runCode() { + // Clear the terminal + clearTerminal(); + + // Get the code from the editor const code = editor.getValue(); const terminal = document.getElementById('terminal'); - terminal.innerHTML += 'Running code...\n'; + + // Run the code using Pyodide try { - let output = await pyodide.runPythonAsync(code); - terminal.innerHTML += `Output:\n${output}\n`; + await pyodide.runPythonAsync(` +import sys +from io import StringIO + +# Create a buffer to capture stdout +output_buffer = StringIO() +sys.stdout = output_buffer + +try: + # Run the user code + ${code.split('\n').map(line => ' ' + line).join('\n')} +except Exception as e: + print(f"Error: {e}") + +# Reset stdout and get the output +sys.stdout = sys.__stdout__ +output = output_buffer.getvalue() +output + `).then(output => { + // console.log(output); + terminal.innerHTML += output; + }); } catch (err) { terminal.innerHTML += `Error:\n${err}\n`; } } + function clearTerminal() { document.getElementById('terminal').innerHTML = ''; }