PyScript is a framework that allows users to create rich Python applications in the browser using HTML’s interface. PyScript aims to give users a first-class programming language that has consistent styling rules, is more expressive, and is easier to learn.
What is PyScript?
PyScript is a programming framework that is used to run Python inside HTML in the browser. PyScript was developed by Peter Wang, Philipp Rudiger, and Fabio Pliger. It was officially launched on April 30, 2022, at the Python US Conference (PyCon US 2022).
Pyscript uses py-script tag or src to execute python code on a web page. This solves the problem of having to use more than one framework, package, or extension to get your code to work.
It also comes with readily available UI components like containers, buttons, and text boxes.
The team from Anaconda cloud which developed PyScript says that in the future they will create support for rich UI and more tags.
How to use PyScript
Once you have added the pyscript.css and physcript.js in your html head, then write your python code inside the opening and closing PyScript tags. That is <py-script>your</py-script> or include external python script using <py-script src=”/python_file.py”></py-script>.
The most basic example provided on PyScript’s website is the following
<html> <head> <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" /> <script defer src="https://pyscript.net/alpha/pyscript.js"></script> </head> <body> <py-script> print('Hello, World!') </py-script> </body> </html>
NOTE: If you want to reduce payload, use pyscript.min.js
Let dig more with Pyscript. We will use
numpy to generate numbers coming from Standard Normal distribution and then plot them using
<html> <head> <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" /> <script defer src="https://pyscript.net/alpha/pyscript.js"></script> <py-env> - numpy - matplotlib </py-env> </head> <body> <h1>Plotting a histogram of Standard Normal distribution</h1> <div id="plot"></div> <py-script output="plot"> import matplotlib.pyplot as plt import numpy as np np.random.seed(42) rv = np.random.standard_normal(1000) fig, ax = plt.subplots() ax.hist(rv, bins=30) fig </py-script> </body> </html>
Hope you find this article interesting , don’t forget share this article with your friends!