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.

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

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.