1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
| (function () { const PYODIDE_BASE = "https://cdn.jsdelivr.net/pyodide/v0.29.2/full/"; const PYODIDE_JS = PYODIDE_BASE + "pyodide.js";
function injectPyodideScriptOnce() { if (window.__pyDemoPyodideScriptPromise) return window.__pyDemoPyodideScriptPromise;
window.__pyDemoPyodideScriptPromise = new Promise((resolve, reject) => { if (window.loadPyodide) return resolve();
const s = document.createElement("script"); s.src = PYODIDE_JS; s.async = true; s.onload = () => resolve(); s.onerror = () => reject(new Error("Failed to load pyodide.js")); document.head.appendChild(s); });
return window.__pyDemoPyodideScriptPromise; }
async function getPyodideOnce() { if (window.__pyDemoPyodide) return window.__pyDemoPyodide; if (window.__pyDemoPyodidePromise) return window.__pyDemoPyodidePromise;
window.__pyDemoPyodidePromise = (async () => { await injectPyodideScriptOnce(); const pyodide = await window.loadPyodide({ indexURL: PYODIDE_BASE }); window.__pyDemoPyodide = pyodide; return pyodide; })();
return window.__pyDemoPyodidePromise; }
function getInlineSource(root) { const ta = root.querySelector("textarea.py-demo__source"); if (ta) return ta.value || ta.textContent || ""; const scr = root.querySelector("script.py-demo__source"); if (scr) return scr.textContent || ""; return ""; }
function extractCodeWithNewlines(node) { if (!node) return "";
const lineEls = node.querySelectorAll( "span.line, span.hljs-ln-line, div.line, div.hljs-ln-line" );
if (lineEls && lineEls.length) { const lines = Array.from(lineEls).map(el => el.textContent);
while (lines.length && !lines[lines.length - 1].trim()) lines.pop();
if (lines.length && lines[lines.length - 1].trim().toUpperCase() === "PYTHON") { lines.pop(); }
return lines.join("\n"); }
const clone = node.cloneNode(true); clone.querySelectorAll("br").forEach(br => br.replaceWith("\n")); let s = clone.textContent || "";
s = s.replace(/\n[ \t]*PYTHON[ \t]*\n?$/i, "\n"); return s; }
function normalizePythonCode(raw) { if (!raw) return ""; let s = String(raw);
s = s.replace(/\r\n?/g, "\n");
s = s.replace(/\u00A0/g, " ");
s = s.replace(/[\u200B-\u200D\uFEFF]/g, "");
s = s.replace(/\t/g, " ");
s = s.replace(/^\s*\n+/, "").replace(/\n+\s*$/, "\n");
return s; }
function dedent(s) { const lines = String(s || "").split("\n"); let minIndent = null;
for (const line of lines) { if (!line.trim()) continue; const m = line.match(/^ +/); const indent = m ? m[0].length : 0; minIndent = (minIndent === null) ? indent : Math.min(minIndent, indent); if (minIndent === 0) break; }
if (!minIndent) return lines.join("\n");
const pad = " ".repeat(minIndent); return lines.map(l => (l.startsWith(pad) ? l.slice(minIndent) : l)).join("\n"); }
function findPrevCodeText(root) { let el = root.previousElementSibling; while (el) { if (el.matches && el.matches("figure.highlight")) { const pre = el.querySelector("td.code pre"); const code = extractCodeWithNewlines(pre); if (code && code.trim()) return code; }
const preCode = el.querySelector && el.querySelector("pre code"); if (preCode) { const code = extractCodeWithNewlines(preCode); if (code && code.trim()) return code; }
if (el.matches && el.matches("pre")) { const code = extractCodeWithNewlines(el); if (code && code.trim()) return code; }
el = el.previousElementSibling; } return ""; }
function buildUI(root, defaultCode, defaultArgv) { root.innerHTML = ` <div class="py-demo__grid"> <div class="py-demo__card"> <div class="py-demo__hint"> 说明:点击运行后才会加载 Pyodide。首次加载会下载运行时,之后通常会被浏览器缓存。 </div> </div>
<div class="py-demo__card"> <label class="py-demo__label">Python 代码(可编辑)</label> <textarea class="py-demo__code"></textarea> </div>
<div class="py-demo__card"> <label class="py-demo__label">模拟命令行参数(相当于:python hello.py ...)</label> <input class="py-demo__argv" placeholder="例如:Alice 或:--help" /> <div class="py-demo__bar"> <button class="py-demo__run">运行</button> <span class="py-demo__status py-demo__hint"></span> </div> </div>
<div class="py-demo__card"> <label class="py-demo__label">输出</label> <pre class="py-demo__out"></pre> </div> </div> `;
const codeEl = root.querySelector(".py-demo__code"); const argvEl = root.querySelector(".py-demo__argv"); codeEl.value = defaultCode || ""; argvEl.value = defaultArgv || ""; }
async function runCode({ code, argv, statusEl }) { statusEl.textContent = "正在加载 Pyodide…(首次可能较慢)";
const pyodide = await getPyodideOnce();
try { statusEl.textContent = "解析依赖并准备运行…"; await pyodide.loadPackagesFromImports(code); } catch (_) {}
statusEl.textContent = "运行中…";
const runner = `import sys, shlex, traceback, io, contextlib argv_str = ${JSON.stringify(argv || "")} sys.argv = ["hello.py"] + shlex.split(argv_str)
_code = ${JSON.stringify(code || "")}
_stdout = io.StringIO() _stderr = io.StringIO()
try: with contextlib.redirect_stdout(_stdout), contextlib.redirect_stderr(_stderr): exec(_code, {"__name__": "__main__"}) except SystemExit: # argparse 的 --help / 参数错误通常会触发 SystemExit pass except Exception: traceback.print_exc(file=_stderr)
_out = _stdout.getvalue() _err = _stderr.getvalue() _result = _out + (("\\n" if _out and _err else "") + _err) _result `; const out = await pyodide.runPythonAsync(runner); statusEl.textContent = "完成。"; return String(out ?? ""); }
function initOne(root) { if (root.dataset.pyDemoInited === "1") return; root.dataset.pyDemoInited = "1";
const from = root.dataset.from || "prev"; const defaultArgv = root.dataset.argv || "";
let defaultCode = ""; if (from === "inline") { defaultCode = getInlineSource(root); } else { defaultCode = findPrevCodeText(root); }
defaultCode = dedent(normalizePythonCode(defaultCode));
buildUI(root, defaultCode, defaultArgv);
const outEl = root.querySelector(".py-demo__out"); const statusEl = root.querySelector(".py-demo__status"); const runBtn = root.querySelector(".py-demo__run"); const codeEl = root.querySelector(".py-demo__code"); const argvEl = root.querySelector(".py-demo__argv");
if (!defaultCode.trim()) { statusEl.textContent = (from === "inline") ? "未找到容器内的源码(.py-demo__source)。" : "未找到上一段代码块,请确认容器紧跟在 Python 代码块后面。"; }
if (!window.__pyDemoQueue) window.__pyDemoQueue = Promise.resolve();
runBtn.addEventListener("click", () => { outEl.textContent = ""; runBtn.disabled = true;
window.__pyDemoQueue = window.__pyDemoQueue.then(async () => { try { const output = await runCode({ code: codeEl.value, argv: argvEl.value, statusEl }); outEl.textContent = output; } catch (e) { outEl.textContent = "[JS Error]\n" + (e && e.stack ? e.stack : String(e)); statusEl.textContent = "运行失败。"; } finally { runBtn.disabled = false; } }); }); }
function initAll() { document.querySelectorAll("[data-py-demo]").forEach(initOne); }
if (document.readyState === "loading") { document.addEventListener("DOMContentLoaded", initAll); } else { initAll(); }
document.addEventListener("pjax:complete", initAll); })();
|