Run Code when PyScript Has Finished
The PyScript loading cycle does many things - loads plugins, instantiates the <py-script>
and <py-repl>
tags, attachs event listeners and so on. To cause something to happen once this entire process is complete, the easiest way is to use a plugin. Plugins can be written in Python or JavaScript; we'll show examples of both.
JavaScript
To run run some JavaScript code when PyScript completes, create a new .js
file with a name of your choice. Here, we'll use example.js
. In this file, add the following:
export default class ExamplePlugin { // the name of the class is unimportant
afterStartup(interpreter){
console.log("Hello, world!") // your code here
}
}
Then add this file to the plugins
list inside the <py-config>
tag, like so:
Python
To run run some Python code when PyScript completes, create a new .py
file with a name of your choice. Here, we'll use example.py
. In this file, add the following:
from pyscript import Plugin # A base class for plugins
class ExamplePlugin(Plugin): # The name of the class is unimportant
def afterSetup(self, interpreter):
print("Hello, world!")
plugin = ExamplePlugin() # The object named 'plugin' will have its methods called
The Interpreter
Argument
In both cases, the interpreter
argument is an interpreter_client object, which wraps the actual interpreter. Key methods include run()
for executing Python code. See the previous link for the source and details.