Introduction
There are times that you want to write pure HTML and JavaScript code and during runtime download and execute Python code based upon various criteria. This article shows how to create the <py-script>
tag, load code into the py-script tag, and finally how to execute the code in the py-script tag.
One limitation that I discovered with PyScript is that you cannot embed HTML tags into Python strings. PyScript will remove HTML tags. I am not sure if this is for security or for another reason. This is simple to solve: create the strings in JavaScript.
I located most of the JavaScript code into a separate module to make the example easier to understand.
Notes:
- Once the
<py-script>
tag is evaluated, the tag can be deleted. Internally, Pyodide copies the Python code into the browser script virtual machine. This might be useful to keep the browser DOM free of clutter (useless tags). - Each time code is loaded into the script virtual machine, it is additive. The new code does not replace the virtual machine’s existing code. Do not accidentally load the same code more than once. There might be a method to clear the script virtual machine and start over, but I do not know how yet.
HTML Code
This example loads into the browser and displays a Loading page ...
message. The Python code located in the pycode
variable will then replace that message with Python loaded and running ...
and then print the current date and time.
The variable pycode
can be loaded from a hardcoded string, or from a server fetch()
. My article PyScript: Loading Python Code in the Browser shows how.
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 |
<!DOCTYPE html> <html> <head> <title>PyScript Tag Create Example</title> <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" /> <script defer src="https://pyscript.net/alpha/pyscript.js"></script> </head> <body> <div id="status">Loading page ...</div> <script src="/exec_py.js"></script> <script> // pycode contains the Python program var pycode = ` from datetime import datetime from js import document document.getElementById("status").innerHTML = 'Python loaded and running ...' print(datetime.now()) `; // Load the code into a py-script tag and then execute run_python(pycode); </script> </body> </html> |
JavaScript Code
This code is fairly simple.
- Create a variable to remember the
<py-script>
tag - Create a DIV to store PyScript program output
- Wrap the Python code with
<py-script
tags - Create a DIV to attach the
<py-script>
tag - Call
evaluate()
to run the attached Python code
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 |
// Global variable to store the py-script DIV var py_div; // Create a DIV store store Python program print output var py_output = document.createElement("div"); py_output.id = "myPyScriptOutput"; document.body.appendChild(py_output); function run_python(py_code) { // remove the previous script tag if (py_div) { py_div.remove(); } // Wrap the Python code (py_code) with a PyScript tag // py_div.evaluate() will run the code within the <py-script> tag let html_tag = ` <py-script output="${py_output.id}"> ${py_code} </py-script> `; // Create the DIV to attach the py-script tag let div = document.createElement("div"); div.innerHTML = html_tag; py_div = div.firstElementChild; document.body.appendChild(py_div); try { // This will run the Python interpreter // for the code loaded into py_div py_div.evaluate(); } catch (error) { console.error("Python error:"); console.error(error); } } |
Summary
Hopefully, this example will help you create browser-based Python applications that have more dynamic abilities. You can load and execute Python code based on events in the browser. In another article, I will show how to store Python scripts locally in the browser virtual file system. This can make your application more resilient to network issues and also help create Single Page Applications (SPA).
More Information
I learned the technique in this article by studying the PyScript and Pyodide source code. This means that things might change in the future since PyScript is in alpha status today.
Photography Credits
I write free articles about technology. Recently, I learned about Pexels.com which provides free images. The image in this article is courtesy of Jean van der Meulen at Pexels.
I design software for enterprise-class systems and data centers. My background is 30+ years in storage (SCSI, FC, iSCSI, disk arrays, imaging) virtualization. 20+ years in identity, security, and forensics.
For the past 14+ years, I have been working in the cloud (AWS, Azure, Google, Alibaba, IBM, Oracle) designing hybrid and multi-cloud software solutions. I am an MVP/GDE with several.
Leave a Reply