implemented output to page console, and updates DOM after every line of code to prevent long waits
parent
e8a50c2c6b
commit
ffb5050b13
114
index.html
114
index.html
|
|
@ -1,53 +1,107 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Python Web Executor</title>
|
||||
<script src="https://cdn.jsdelivr.net/pyodide/v0.24.0/full/pyodide.js"></script>
|
||||
<title>Pyodide Real-Time Python Execution with Console</title>
|
||||
<script src="https://cdn.jsdelivr.net/pyodide/v0.23.4/full/pyodide.js"></script>
|
||||
<style>
|
||||
body { font-family: Arial, sans-serif; text-align: center; }
|
||||
textarea { width: 80%; height: 150px; }
|
||||
button { margin-top: 10px; }
|
||||
pre { background: #f4f4f4; padding: 10px; }
|
||||
#console {
|
||||
width: 100%;
|
||||
height: 200px;
|
||||
background-color: black;
|
||||
color: white;
|
||||
font-family: monospace;
|
||||
padding: 10px;
|
||||
overflow-y: auto;
|
||||
border: 1px solid #ccc;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h2>Python Web Executor</h2>
|
||||
<textarea id="code" placeholder="Write Python code here..."></textarea><br>
|
||||
<button onclick="runPython()">Run</button>
|
||||
<pre id="output"></pre>
|
||||
<h1>Real-Time Python Execution with Pyodide</h1>
|
||||
<textarea id="python-code" rows="10" cols="50" placeholder="Enter your Python code here..."></textarea>
|
||||
<br><br>
|
||||
<button id="compile-button">Compile and Run</button>
|
||||
<br><br>
|
||||
<h2>Console Output:</h2>
|
||||
<div id="console"></div>
|
||||
|
||||
<script>
|
||||
async function loadPyodideAndSetup() {
|
||||
window.pyodide = await loadPyodide();
|
||||
await pyodide.runPythonAsync(`
|
||||
async function initializePyodide() {
|
||||
let pyodide = await loadPyodide({
|
||||
indexURL: "https://cdn.jsdelivr.net/pyodide/v0.23.4/full/"
|
||||
});
|
||||
|
||||
// Redirect Python's stdout and stderr to the console area
|
||||
pyodide.runPython(`
|
||||
import sys
|
||||
from js import console
|
||||
def move_forward():
|
||||
print("Moving forward!")
|
||||
def turn_left():
|
||||
print("Turning left!")
|
||||
def fire():
|
||||
print("Firingg!")
|
||||
globals()['move_forward'] = move_forward
|
||||
globals()['turn_left'] = turn_left
|
||||
globals()['fire'] = fire
|
||||
import asyncio
|
||||
from js import document
|
||||
|
||||
class ConsoleOutput:
|
||||
def write(self, text):
|
||||
console = document.getElementById("console")
|
||||
console.textContent += text
|
||||
console.scrollTop = console.scrollHeight # Auto-scroll to bottom
|
||||
|
||||
def flush(self):
|
||||
pass
|
||||
|
||||
sys.stdout = ConsoleOutput()
|
||||
sys.stderr = ConsoleOutput()
|
||||
`);
|
||||
|
||||
return pyodide;
|
||||
}
|
||||
|
||||
async function runPython() {
|
||||
let code = document.getElementById("code").value;
|
||||
let outputElement = document.getElementById("output");
|
||||
async function runPythonCode(pyodide, code) {
|
||||
try {
|
||||
let result = await pyodide.runPythonAsync(code);
|
||||
outputElement.textContent = result !== undefined ? result.toString() : "";
|
||||
// Clear the console before running new code
|
||||
document.getElementById("console").textContent = "";
|
||||
|
||||
// Run the Python code asynchronously
|
||||
console.log(code);
|
||||
function addExtraLineWithIndent(inputString, additionalText = "") {
|
||||
// Split the string into an array of lines
|
||||
const lines = inputString.split('\n');
|
||||
const result = lines.map(line => {
|
||||
// Check if the line ends with a colon
|
||||
if (line.trim().endsWith(":")) {
|
||||
return line; // Leave it as is
|
||||
}
|
||||
// Extract leading whitespace (indentation) from the current line
|
||||
const indentation = line.match(/^\s*/)[0];
|
||||
// Add the original line and the new inserted line with indentation
|
||||
return line + '\n' + indentation + additionalText;
|
||||
}).join('\n'); // Combine the lines back into a single string
|
||||
return result;
|
||||
}
|
||||
|
||||
// Example usage
|
||||
const input = " Line 1\n Line 2\nLine 3";
|
||||
const output = addExtraLineWithIndent(code, "await asyncio.sleep(0.01)");
|
||||
console.log(output);
|
||||
|
||||
|
||||
await pyodide.runPythonAsync(output);
|
||||
} catch (err) {
|
||||
outputElement.textContent = "Error: " + err;
|
||||
// Display any errors in the console area
|
||||
document.getElementById("console").textContent += `Error: ${err}\n`;
|
||||
}
|
||||
}
|
||||
|
||||
loadPyodideAndSetup();
|
||||
document.addEventListener("DOMContentLoaded", async () => {
|
||||
let pyodide = await initializePyodide();
|
||||
|
||||
document.getElementById("compile-button").addEventListener("click", async () => {
|
||||
let code = document.getElementById("python-code").value;
|
||||
await runPythonCode(pyodide, code);
|
||||
});
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
|
|
@ -0,0 +1,139 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Python Web Executor</title>
|
||||
<script src="https://cdn.jsdelivr.net/pyodide/v0.24.0/full/pyodide.js"></script>
|
||||
<style>
|
||||
body {
|
||||
font-family: Arial, sans-serif;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
textarea {
|
||||
width: 80%;
|
||||
height: 150px;
|
||||
}
|
||||
|
||||
button {
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
pre {
|
||||
background: #f4f4f4;
|
||||
padding: 10px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h2>Python Web Executor</h2>
|
||||
<textarea id="code" placeholder="Write Python code here..."></textarea><br>
|
||||
<button onclick="runPython()">Run</button>
|
||||
<h3>Console Output:</h3>
|
||||
<pre id="console-output"></pre>
|
||||
|
||||
<script>
|
||||
async function loadPyodideAndSetup() {
|
||||
window.pyodide = await loadPyodide();
|
||||
|
||||
// Define the external JavaScript print function
|
||||
function jsPrint(text) {
|
||||
console.log(text); // Log to the browser console
|
||||
const outputElement = document.getElementById("console-output");
|
||||
outputElement.textContent += text + "\n"; // Append to visible console
|
||||
}
|
||||
|
||||
// Expose jsPrint to Python
|
||||
window.jsPrint = jsPrint;
|
||||
|
||||
// Redirect Python's stdout to JavaScript and override time.sleep()
|
||||
await pyodide.runPythonAsync(`
|
||||
import asyncio
|
||||
import time
|
||||
import sys
|
||||
from js import jsPrint
|
||||
|
||||
class JSConsoleWriter:
|
||||
def write(self, text):
|
||||
jsPrint(text)
|
||||
def flush(self):
|
||||
pass
|
||||
|
||||
sys.stdout = JSConsoleWriter()
|
||||
|
||||
# Override time.sleep to add periodic yielding
|
||||
def sleep(seconds):
|
||||
loop = asyncio.get_event_loop()
|
||||
if loop.is_running():
|
||||
# If we're inside an async environment, yield control back to browser
|
||||
coro = asyncio.sleep(seconds)
|
||||
loop.run_until_complete(coro)
|
||||
time.sleep(seconds)
|
||||
else:
|
||||
# Fallback for non-async environments
|
||||
print(":-(")
|
||||
time.sleep(seconds)
|
||||
|
||||
#time.sleep = non_blocking_sleep
|
||||
`);
|
||||
}
|
||||
|
||||
|
||||
// JavaScript functions for controlling the tank
|
||||
function fire2() {
|
||||
console.log("Tank fired!");
|
||||
document.getElementById("console-output").textContent += "Tank fired!\n";
|
||||
}
|
||||
|
||||
function move_forward() {
|
||||
console.log("Tank moved forward!");
|
||||
document.getElementById("console-output").textContent += "Tank moved forward!\n";
|
||||
}
|
||||
|
||||
|
||||
|
||||
async function runPython() {
|
||||
let code = document.getElementById("code").value;
|
||||
let consoleOutput = document.getElementById("console-output");
|
||||
consoleOutput.textContent = ""; // Clear the console before running
|
||||
|
||||
try {
|
||||
// Define a helper function in Python to yield back control
|
||||
await pyodide.runPythonAsync(`
|
||||
import sys
|
||||
import time
|
||||
from js import jsPrint
|
||||
|
||||
class JSConsoleWriter:
|
||||
def write(self, text):
|
||||
jsPrint(text)
|
||||
def flush(self):
|
||||
pass
|
||||
|
||||
sys.stdout = JSConsoleWriter()
|
||||
`);
|
||||
|
||||
// Run the user code directly, no wrapping or indentation modification
|
||||
await pyodide.runPythonAsync(code);
|
||||
|
||||
// Introduce periodic yielding back to the browser
|
||||
for (let i = 0; i < code.split("\n").length; i++) {
|
||||
await new Promise(resolve => setTimeout(resolve, 0)); // Yield to the browser
|
||||
}
|
||||
} catch (err) {
|
||||
consoleOutput.textContent += "Error: " + err + "\n";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
loadPyodideAndSetup();
|
||||
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
Loading…
Reference in New Issue