PyScript Tutorial | Run Python Script in the Web BrowserIn 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.
PrerequisiteBefore moving further, we should have -
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 PyScriptFollowing are the feature of the PyScript -
Project Setup for PyScriptBefore 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 StartedFirst 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 -
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.
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 PyScriptIt 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 PyScriptExternal 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.
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 fileNow, 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 REPLPython 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 - 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 PyScriptNow 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 modulesNow 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 LibraryPyScript, 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:
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.
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 PackageInstead of using Python built-in modules, we can also use third-party libraries which shipped in Pyodide, such as -
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 PyScriptIn 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 classPyScript 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:
ConclusionWe 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. Next TopicPython FlashText Module |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India