Run Python Directly In HTML With PyScript
7 min read
Imagine writing your favourite programming language everywhere and not being limited by the terminal. Yes, you can now write Python code in the browser HTML and render it with PyScript and it is quite easier than you think.
🌟 What is PyScript?
PyScript is a framework that allows users to create rich Python applications in the browser using HTML's interface and the power of Pyodide, WASM and modern web technologies.
Pyodide is a port of CPython to WebAssembly/Emscripten. Pyodide makes it possible to install and run Python packages in the browser. Visit the REPL here to play with it.
The PyScript framework provides users at every experience level with access to an expressive, easy-to-learn tool with countless applications.
PyScript is a Pythonic alternative to Scratch, JSFiddle, and other "easy to use" programming frameworks, with the goal of making the web a friendly, hackable place where anyone can author interesting and interactive applications.
🌟 Introduction to PyScript
To get started see the getting started tutorial but let's see how to use the three most useful tags now when using PyScript.
I will basically do a
Hello World Program from PyScript today, and I will be building small web apps, some scraping with it and other related PyScript tutorials in the near future as it gets better.
It can be used to define python code that is executable within the web page. The element itself is not rendered to the page and is only used to add logic.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" /> <script defer src="https://pyscript.net/alpha/pyscript.js"></script> <title>Hello PyScript</title> </head> <body> <py-script> print('Hello PyScript') def hello(): return 'Hello PyScript from a function' hello() </py-script> </body> </html>
So we basically added it in order to write our Python with
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" /> <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
defer in the script tag is a Boolean value, used to indicate that script is executed after the document has been parsed. It works with external scripts.
As you can see from my file, indentation is really important even when writing Python in HTML.
To run the above file, you can either click on it and load it with Chrome but I would recommend using a live server (VS Code Extension) or easily serve it with Python's
http.server module by running;
python -m http.server
http.server module can be invoked directly using the
-m switch of the interpreter. This serves files relative to the current directory but you might have to refresh for changes, unlike Live Server.
Yeah, it is really clunky and slow...
What if the codebase becomes too big, you won't write all that in the
py-script tags, so you can now create a Python file in the same root folder.
So you can add it in the
src attribute like this;
So our new changes;
What if you have modules and you want to be able to use some of those. If you are working with built-in python libraries is simple, you just import them as you would usually do in python.
So let's try the
math library. Add another
py-script tag for this;
<py-script> # Standard Python Libraries import math squares = [math.sqrt(i) for i in [4,16,36,64]] print(squares) </py-script>
Our new output;
What if we want to use external modules. This introduces us to the second PyScript tag which can be declared in the tag and a list of these libraries is outlined.
<py-env> - numpy </py-env>
py-script tag in the body;
<py-script> # External Supported Libraries import numpy as np arr = np.array([2,4,6,8]) print("Square Value of arr : ", np.square(arr)) </py-script>
Obviously, you can add some styling with another file or bootstrap to have them representable and that is my little challenge to you if you are a front-end dev.
This creates a REPL component that is rendered to the page as a code editor and allows users to write executable code.
Just add this under our
<py-script> print("Interactive Shell;") </py-script> <py-repl> </py-repl>
Then in our interactive shell after loading the server, add this in the REPL and execute or hit
Shift + Enter.
import math math.sqrt(4)
Visit this repo for the full code of this introduction 🚀.
🌟 Downloading the zip (Clone)
Please make sure to move the extracted files to the root of your main HTML file if you are going to use the offline version after compiling it with Node.
There is currently no proper documentation around this but you can stay posted by watching the repo or stay updated here.
🌟 Is PyScript a programming language?
Developed by the Anaconda team, the project’s ultimate goal is to allow a much wider audience (for example, front-end developers) to benefit from the power of Python and its various libraries (statistical, ML/DL, etc.).
It might not as of now because it is still in an Alpha stage and can only get to compete with Django, and Flask because you do not need Jinja, templates anymore.
Maybe Django developers will find this way easier, especially when it is enhanced and improved significantly over time and I can't wait for that time personally.
Data scientists have already embraced this tool and those who wish to share the results of their research can do it more easily now. Maybe we can see some new fields of front-end development coming up.
🌟 Note 🌟
This is an extremely experimental project, so expect things to break and when using the CDN version, it can take some significant time to load the runtime!
It has been only tested on Chrome at the moment and may not fully support other browsers.
The alpha release of PyScript can be found on PyScript website. The code is available here. For more examples visit this folder.
It is really promising, but it can potentially open quite a lot of new other security issues which I believe will be addressed gradually when we get the first stable version.
There are limits to the libraries you can use currently, please visit Pyodide Supported modules for more information.
I am personally curious to see where it will lead us too and I believe its future is so bright with over 10k + Stargazers by the time of writing this post and it is barely a few months out.
I forked the project a few weeks ago and I would personally start contributing to it because I am excited to see its future and usefulness come to life.
🌟 Notes & Resources
📌 PyScript: Python in the Browser - Anaconda Article
📌 PyScript Official Website
📌 PyScript Official Repo
Once again, hope you learned something today from my little closet.
Please consider subscribing or following me for related content, especially about Tech, Python & General Programming.
You can show extra love by buying me a coffee to support this free content and I am also open to partnerships, technical writing roles, collaborations and Python-related training or roles.