Skip to content

Commit

Permalink
Merge pull request #455 from live-codes/patch-pyodide-input
Browse files Browse the repository at this point in the history
patch pyodide input
  • Loading branch information
hatemhosny authored Oct 17, 2023
2 parents eea5d73 + c86d8ee commit bc2a62d
Showing 1 changed file with 29 additions and 6 deletions.
35 changes: 29 additions & 6 deletions src/livecodes/languages/python-wasm/lang-python-wasm-script.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,24 @@ window.addEventListener('load', async () => {
scripts.forEach((script) => (code += script.innerHTML + '\n'));

async function main() {
// already loaded
if (livecodes.pyodideLoading === false) return;
livecodes.pyodide = await loadPyodide({
indexURL: pyodideBaseUrl,
// still loading
if (livecodes.pyodideLoading) {
await livecodes.pyodideLoading;
return;
}
// start loading
livecodes.pyodideLoading = new Promise<void>(async (resolve) => {
livecodes.pyodide = await loadPyodide({
indexURL: pyodideBaseUrl,
});
await livecodes.pyodide.loadPackage('micropip');
livecodes.micropip = livecodes.pyodide.pyimport('micropip');
livecodes.pyodideLoading = false;
resolve();
});
await livecodes.pyodide.loadPackage('micropip');
livecodes.micropip = livecodes.pyodide.pyimport('micropip');
livecodes.pyodideLoading = false;
await livecodes.pyodideLoading;
}

async function cleanUp() {
Expand All @@ -34,11 +45,22 @@ window.addEventListener('load', async () => {
livecodes.pyodide.pyodide_py._state.restore_state(livecodes.pyodideState);
} catch (err) {
// if restoring state fails, reload pyodide
livecodes.pyodideLoading = true;
livecodes.pyodideLoading = undefined;
await main();
}
}

async function prepareEnv() {
await pyodideReady;
const patchInput = `
from js import prompt
def input(p):
return prompt(p)
__builtins__.input = input
`.trim();
await livecodes.pyodide.runPythonAsync(patchInput);
}

async function loadPackagesInCode(code: string) {
const packages = [...livecodes.pyodide.pyodide_py.code.find_imports(code)];
const newPackages = packages.filter((p) => !(p in livecodes.pyodide.loadedPackages));
Expand All @@ -54,6 +76,7 @@ window.addEventListener('load', async () => {
async function evaluatePython(code: string) {
await pyodideReady;
await cleanUp();
await prepareEnv();
await loadPackagesInCode(code);
try {
livecodes.pyodideState = livecodes.pyodide.pyodide_py._state.save_state();
Expand Down

0 comments on commit bc2a62d

Please sign in to comment.