What is PyScript?

Overview

PyScript is an open-source framework that helps developers to create Python scripts using HTML files. These documents run the script in browsers.

Python is the most commonly used language by developers. It has a very easy syntax and vast applications in backend web development, artificial intelligence, machine learning, and data science. Python was never used in front-end web development until PyCon 2022 conference, where the team from Anaconda announced PyScript.

PyScript is created using technologies like Emscripton, Pyodide, and WASM to provide a clean API. PyScript with JavaScript, HTML, and CSS allows developers to become more flexible and have more power in the frontend.

Note: You can get more information about emsctiption, WASM assembly language and Pyodide.

PyScript setup

We do not need to download any large files to use PyScript. Instead, we can use it in simple HTML documents using the link tag.

<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>

Note: We can also use PyScript by manually downloading the files from this link.

Syntax

Like all HTML tags, PyScript has a tag to use to write Python code. We can use the following tag to tell the browser that the lines in the tag are Python script and need to be executed in PyScript.

<py-script> 
 ### write python code here
</py-script>

Example

The following example shows a PyScript linking to an HTML file and running a Python script. The Python script generates a random password of length 10 and prints it on the browser.

Running a random password generator of length 10 python script using PyScript in html file

Reasons to use PyScript

The following are a few main reasons to use PyScript in web development.

  • Huge libraries: PyScript allows the developers to use Python’s huge libraries such as NumPy, Pandas, Matplotlib, and many more.
  • User interface development: PyScript will enable developers to build accessible components like buttons.
  • Browsers support: PyScript allows developers to host applications without servers’ need.
  • Easy management: PyScript allows developers to manage files and packages of the applications to run efficiently.

PyScript is very useful in making small Python web applications where we don't need a lot of computation on the browsers.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved