|
| 1 | +<!DOCTYPE html> |
| 2 | +<html lang="en"> |
| 3 | +<head> |
| 4 | +<meta charset="UTF-8" /> |
| 5 | +<title>Python Editor with Pyodide</title> |
| 6 | + |
| 7 | +<!-- CodeMirror CSS --> |
| 8 | +<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.10/codemirror.min.css" /> |
| 9 | + |
| 10 | +<style> |
| 11 | + body { font-family: Arial, sans-serif; margin: 20px; } |
| 12 | + #editor { height: 300px; border: 1px solid #ccc; } |
| 13 | + #output { border: 1px solid #ccc; padding: 10px; white-space: pre-wrap; margin-top: 10px; background: #f9f9f9; } |
| 14 | + button { margin-top: 10px; } |
| 15 | +</style> |
| 16 | +</head> |
| 17 | +<body> |
| 18 | + |
| 19 | +<h2>Python Editor & Interpreter</h2> |
| 20 | +<textarea id="editor">print("Hello, Python!")</textarea><br/> |
| 21 | +<button id="runBtn">Run Code</button> |
| 22 | + |
| 23 | +<h3>Output:</h3> |
| 24 | +<div id="output"></div> |
| 25 | + |
| 26 | +<!-- Load CodeMirror --> |
| 27 | +<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.10/codemirror.min.js"></script> |
| 28 | +<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.10/mode/python/python.min.js"></script> |
| 29 | + |
| 30 | +<!-- Load Pyodide --> |
| 31 | +<script src="https://cdn.jsdelivr.net/pyodide/v0.23.4/full/pyodide.js"></script> |
| 32 | + |
| 33 | +<script> |
| 34 | + // Initialize CodeMirror editor |
| 35 | + var editor = CodeMirror.fromTextArea(document.getElementById("editor"), { |
| 36 | + mode: "python", |
| 37 | + lineNumbers: true, |
| 38 | + indentUnit: 4, |
| 39 | + tabSize: 4, |
| 40 | + }); |
| 41 | + |
| 42 | + // Load Pyodide interpreter |
| 43 | + let pyodideReadyPromise = loadPyodide(); |
| 44 | + |
| 45 | + document.getElementById("runBtn").addEventListener("click", async () => { |
| 46 | + const outputElem = document.getElementById("output"); |
| 47 | + outputElem.textContent = "Running..."; |
| 48 | + try { |
| 49 | + const pyodide = await pyodideReadyPromise; |
| 50 | + let code = editor.getValue(); |
| 51 | + let result = await pyodide.runPythonAsync(code); |
| 52 | + outputElem.textContent = result === undefined ? "" : result.toString(); |
| 53 | + } catch (err) { |
| 54 | + outputElem.textContent = err; |
| 55 | + } |
| 56 | + }); |
| 57 | +</script> |
| 58 | + |
| 59 | +</body> |
| 60 | +</html> |
0 commit comments