mirror of
https://github.com/pyscript/pyscript.git
synced 2026-04-30 16:00:32 -04:00
introduce outputmanager to redirect output in repl
This commit is contained in:
@@ -202,28 +202,32 @@ export class PyRepl extends HTMLElement {
|
||||
async evaluate() {
|
||||
console.log('evaluate');
|
||||
let pyodide = await pyodideReadyPromise;
|
||||
// debugger
|
||||
|
||||
try {
|
||||
// @ts-ignore
|
||||
let source = this.editor.state.doc.toString();
|
||||
const sourceStrings = [`output_manager.change("`+this.editorOut.id+`")`,
|
||||
...this.editor.state.doc.toString().split("\n")];
|
||||
const source = sourceStrings.join('\n')
|
||||
let output;
|
||||
|
||||
if (source.includes("asyncio")){
|
||||
output = await pyodide.runPythonAsync(source);
|
||||
await pyodide.runPythonAsync(`output_manager.revert()`)
|
||||
}else{
|
||||
output = pyodide.runPython(source);
|
||||
pyodide.runPython(`output_manager.revert()`)
|
||||
}
|
||||
|
||||
|
||||
if (output !== undefined){
|
||||
let Element = pyodide.globals.get('Element');
|
||||
let out = Element(this.editorOut.id);
|
||||
|
||||
// @ts-ignore
|
||||
out.write(output);
|
||||
out.write.callKwargs(output, { append : false});
|
||||
out.write.callKwargs(output, { append : true});
|
||||
|
||||
if (!this.hasAttribute('target')) {
|
||||
this.editorOut.hidden = false;
|
||||
}
|
||||
// this.addToOutput(output);
|
||||
}
|
||||
|
||||
if (this.hasAttribute('auto-generate')) {
|
||||
|
||||
@@ -8,7 +8,7 @@ let pyodide;
|
||||
let additional_definitions = `
|
||||
from js import document, setInterval, console
|
||||
import asyncio
|
||||
import io, base64
|
||||
import io, base64, sys
|
||||
|
||||
loop = asyncio.get_event_loop()
|
||||
|
||||
@@ -95,7 +95,30 @@ class Element:
|
||||
|
||||
return Element(clone.id, clone)
|
||||
|
||||
class OutputManager:
|
||||
def __init__(self, custom=None, output_to_console=True):
|
||||
self._custom = custom
|
||||
self.output_to_console = output_to_console
|
||||
self.prev = None
|
||||
|
||||
def change(self, custom):
|
||||
self._prev = self._custom
|
||||
self._custom = custom
|
||||
console.log("----> changed to", self._custom)
|
||||
|
||||
def revert(self):
|
||||
console.log("----> reverted")
|
||||
self._custom = self._prev
|
||||
|
||||
def write(self, txt):
|
||||
if self._custom:
|
||||
pyscript.write(self._custom, txt, append=True)
|
||||
if self.output_to_console:
|
||||
console.log(self._custom, txt)
|
||||
|
||||
pyscript = PyScript()
|
||||
output_manager = OutputManager()
|
||||
sys.stdout = output_manager
|
||||
`
|
||||
|
||||
let loadInterpreter = async function(): Promise<any> {
|
||||
|
||||
Reference in New Issue
Block a user