Javatpoint Logo
Javatpoint Logo

PyScript Tutorial | Run Python Script in the Web Browser

In this tutorial, we will learn about the newly introduced Python library or we can say new feature PyScript. This library allows us to run the Python script on the web browser. Python provides the many features that make programmer life easier. Now, they came with the new feature that can integrate the Python program on the front-end.

For the long time, JavaScript is most popular and dominant language in the front-end development. It can run natively in the browser and interact with HTML and CSS through the DOM API. But things are started change with the arrival of WebAssembly. Now many languages such as C, C++, and many others can now run in the browser at good speed. Then why should Python remain untouched by this feature?

PyScript is a system for interleaving Python in the HTML. We will cover the following topics in this tutorial.

  • What is PyScript?
  • How does PyScript work?
  • Project Setup for PyScript
  • Setting up project folder for PyScript locally.
  • Getting Started
  • Internal PyScript
  • External PyScript
  • Using Python third-party module in Python
  • Conclusion

Prerequisite

Before moving further, we should have -

  • A basic understanding of the HTML, CSS, and JavaScript.
  • A decent knowledge of Python programming language.
  • A web server. We will create the sample server using Python, so Python should be installed in the system.
  • A web browser, Chrome is recommended as per the PyScript official documentation.

What is PyScript?

PyScript is an open-source Python framework that provides the facility to create the frontend web application using Python. It means we can write and run code in HTML. PyScript allows us to either embedded Python code in HTML or link to a Python file and the code will run in the browser. We don't need to run Python in backend.

PyScript was developed by the Anaconda and make public on April 30 at PyCon US 2022. At the time of writing, PyScript is in development phase and teams are actively working on it. So we can expect the breaking changes and newer feature since it hasn't been stably released yet.

How Does PyScript Work?

PyScript is basically based on pyodide which means "port of CPython to web assembly/Emscripten" project. WebAssembly is a low-level binary format that allows us to write programs in other languages, which are then executed in the browser. The CPython allows us to install and run Python packages on browser while PyScript abstract allows us to developing frontend apps with Python in the browser.

Features of PyScript

Following are the feature of the PyScript -

  • It allows us to embed the Python code into HTML.
  • We don't need to worry about the deployment because we are using pyscript. Everything is handled by the web browser. We can exchange HTML files containing refined dashboards or any charts data with anyone.
  • PyScript consists of three primary parts - py-env, py-script, and py-repl. We will do through later.

Project Setup for PyScript

Before start working with the PyScript, let's create a directory where our code will take place.

Open the terminal and create the project directory using the below command.

Now open the directory in visual studio or Pycharm. Now we are ready to implement PyScript.

Getting Started

First we will create the HTML file and add links to the PyScript assests comprising of a CSS file and JavaScript file in the <head> section of an HTML page. Once we done with the assests, we can use PyScript in an HTML file in the either of two ways -

  • Internal Pyscript

As its name suggest, we can embed the Python code within <py-script> tag in an HTML. The <py-script> tag can be added in the <head> or <body> tag depending on the task at hand.

  • External PyScript

In this approach, we write the code with .py extension, which can be then reference in the <py-script> tag using the src attribute.

Let's understand the internal PyScript

Internal PyScript

It is a easiest and quicker way to start using PyScript is to embed Python code in the HTML file.

In our working directory, create a hello_pyscript.html file and add the following script.

Example -

In the above code, we add the pyscript.css in <head> section. It contains style for PyScript visual components, REPL, the PyScript loader, etc. Then, we link to pyscript.js file, which contains the necessary features for using PyScript like creating tag <py-script> where we can write our Python code.

Now save the file in the root of project directory and open the hello_script.html file in the Chrome.

External PyScript

External PyScript is a better and more scalable approach to add code. Below are few of the reason to use PyScript code in an external file.

  • The browser caches the file which enhances the performance.
  • We can reference the file in multiple pages, reducing duplication.
  • Python code can be formatted using the other tools like black or Python linters. These tools don't currently work on Python code embedded in an HTML.

To implement PyScript external, we need to create the index.html file and a Python file that we want to embed.

Creating the index.html file

Create an index.html file and link to the PyScript assets.

Currently, this file won't work because we are just linking to the PyScript resources. To make it working, we need to create the main.py file our Python will take place.

Creating the main.py

In the main.py file, we are creating a Python function that prints greeting message. Let's create the main.py file.

The above function takes a name parameter and prints a greetings message with the name stored in the name parameter. When this function is called, it will print Hi, Peter Parker.

Embed the main.py file in HTML file

Now, we will link the main.py file in the index.html file. Open the index.html add the line style the body tag.

Example -

As we can observe, we add the src tag which takes the file name along with the path.

In the upcoming section, we will refer an external Python file, which will require us to use a server to avoid CORS errors.

Using the PyScript REPL

Python provides a Read-Eval-Print Loop (REPL) which we can use to experiment and try out Python code.

To use the REPL, add the <py-repl> tag in the body tag in our index.html file.

Here we can use all the functionalities; such as evaluate expression, create function and many other things. To see what an expression evaluates, we need to click the green Play icon.

Below is some of the operations we can see that -

Example -

PyScript Tutorial | Run Python Script in the Web Browser

Output:

31536000.0
The sum of a + b =
30

Now we got an idea how to use REPL, next we will learn how to create and use modules in Python.

Using Python Module in PyScript

Now we will create the Python custom module and use it our HTML code. We will also import the modules from Python standard library, as well as third-party modules.

PyScript provides the <py-env> which allows us to reference modules or module file paths.

Creating custom modules

Now we are defining the two functions in my_module.py file in our project directory. Let's add the following line of code.

my_module.py

Now, we are creating modules.html file and add the following code.

In the above code, we use the <py-env> inside the body tag, which takes a YAML list that has paths as its key. The my_module.py is a file path of the custom module relative to modules.html file. Once the path to the custom module is specified, PyScript will import module in the file.

We imported the multiply function from the my_module module. When, we start server, we can see the following output.

Importing modules from the Python standard Library

PyScript, as we discussed earlier Python is written upon the Pyodide, which provides access to a lot of modules available in the Python standard library that are ready for you to use, with the exception of the following:

  • venv
  • Tkinter
  • dbm

According to the official documentation of the Pyodide documentation, the following modules can be imported but these are not functional due to limitation of the WebAssembly VM.

  • multiprocessing
  • threading
  • sockets

We modify the Python code in the <py-script> tag to generate a random number using the random module.

Example -

When we visit to the server, we will see the random number that is generated each time when we refresh the page.

Using third-party Package

Instead of using Python built-in modules, we can also use third-party libraries which shipped in Pyodide, such as -

  • pytest
  • Jinja2
  • beautifulsoup4
  • Numpy
  • Pandas
  • Matplotlib
  • PIL
  • scikit-learn

Create a new HTML file and add the following code -

Example -

In the above code we add the <py-env> tag, which includes the list of third-party packages that we want to use in our project, - Numpy and Matplotlib packages. Next, in the <py-script> tag, we import NumPy as np and Matplotlib as plt. Then, we call NumPy's array method, which creates an array that is then stored in the arr variable. After that, we call the Matplotlib's plot method with the array arr as an argument to plot a graph.

Output -

Now, we have explained how we can use custom module, inbuilt module and third-party packages. We will discuss how to access and manipulate HTML elements in the next section.

How to Access and Manipulate HTML Element using PyScript

In this part of tutorial, we will learn to select an HTML element using an ID or a CSS class, modifies an element, attach events to an element, and create new elements using PyScript.

Using the Element class

PyScript sends with the Element class, which permits us to select an HTML element using its ID.

To understand it, create a new html file elements.html file and insert the following code -

Example -

In the above code, we use the <ul> element with an ID of navigation in the <body> tag. We will use the ID to select this element using the Element class. The selected instance will give us methods that we can use to select the descendants and manipulate them.

We have used another <div> tag with an ID of output. We will make change its innerHTML to write a new value. Then we linked ge_element.py file that will contain our Python code. Now, let's create get_element.py file, and add the following file.

Example - get_element.py

In the above code, we use the Element class to access the <ul> element using the navigation ID.

When an element is selected using the Element class, we can take advantage of some of the following methods:

  • write() - It sets the innerHTML value.
  • select() - It uses a CSS selector to find descendant elements.
  • add_class() - It adds one or more classes to an element.
  • remove_class() - It removes one or more classes from an element

Conclusion

We have covered important topics of the PyScript and you have decent idea of this framework. This tutorial included its introduction, how it works, and features. We can use Pyscript in our HTML easily. We can either use Python script internal or external. PyScript is undoubtedly an interesting new technology that permits you to run Python code in the web browser thanks to Pyodide and WebAssembly.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA