Export Runtime from PyScript Module (#868)

* export 'pyscript' JS module with runtime attribute, to allow accessing (Pyodide) runtime and globals from JS.
* add docs to explain the js module
* add integration tests for the js module

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
This commit is contained in:
Jeff Glass
2022-10-23 13:46:19 -05:00
committed by GitHub
parent aa85f5f596
commit d9b8b48972
7 changed files with 157 additions and 6 deletions

View File

@@ -27,7 +27,7 @@ export default {
sourcemap: true,
format: "iife",
inlineDynamicImports: true,
name: "app",
name: "pyscript",
file: "build/pyscript.js",
},
{

View File

@@ -57,6 +57,7 @@ class PyScriptApp {
config: AppConfig;
loader: PyLoader;
runtime: Runtime;
// lifecycle (1)
main() {
@@ -111,13 +112,13 @@ class PyScriptApp {
"Only the first will be used");
}
const runtime_cfg = this.config.runtimes[0];
const runtime: Runtime = new PyodideRuntime(this.config, runtime_cfg.src,
this.runtime = new PyodideRuntime(this.config, runtime_cfg.src,
runtime_cfg.name, runtime_cfg.lang);
this.loader.log(`Downloading ${runtime_cfg.name}...`);
const script = document.createElement('script'); // create a script DOM node
script.src = runtime.src;
script.src = this.runtime.src;
script.addEventListener('load', () => {
void this.afterRuntimeLoad(runtime);
void this.afterRuntimeLoad(this.runtime);
});
document.head.appendChild(script);
}
@@ -209,3 +210,5 @@ globalExport('pyscript_get_config', pyscript_get_config);
// main entry point of execution
const globalApp = new PyScriptApp();
globalApp.main();
export const runtime = globalApp.runtime

View File

@@ -0,0 +1,42 @@
from .support import PyScriptTest
class TestRuntimeAccess(PyScriptTest):
"""Test accessing Python objects from JS via pyscript.runtime"""
def test_runtime_python_access(self):
self.pyscript_run(
"""
<py-script>
x = 1
def py_func():
return 2
</py-script>
"""
)
self.page.add_script_tag(
content="""
console.log(`x is ${pyscript.runtime.globals.get('x')}`);
console.log(`py_func() returns ${pyscript.runtime.globals.get('py_func')()}`);
"""
)
assert self.console.log.lines == [
self.PY_COMPLETE,
"x is 1",
"py_func() returns 2",
]
def test_runtime_script_execution(self):
"""Test running Python code from js via pyscript.runtime"""
self.pyscript_run("")
self.page.add_script_tag(
content="""
const interpreter = pyscript.runtime.interpreter;
interpreter.runPython('console.log("Interpreter Ran This")');
"""
)
assert self.console.log.lines == [self.PY_COMPLETE, "Interpreter Ran This"]