PyScript - Run Python in your Browser!
Tags: python, javascript
Published: 2022-06-04 18:49:13

#### Python has grown in popularity dramatically in recent years. It has a wide range of applications, including AI, data science, robotics, and scripting, to mention a few.

Python is mostly used in the backend in web development, with frameworks such as Django and Flask.

Python formerly lacked front-end capabilities in comparison to other languages such as JavaScript. However, Python programmers have created libraries (such as [Brython](https://brython.info/)) to let their favourite language run on the web.

This year, during the [PyCon 2022 conference](https://youtube.com/playlist?list=PL2Uw4_HvXqvYeXy8ab7iRHjA-9HiYhRQl), Anaconda launched PyScript, a framework that allows you to utilise Python on the web using regular HTML.

Here's a tweet regarding the launch:

{% embed https://twitter.com/anacondainc/status/1520447158603890691?s=20&t=9dGZQZr6FPCZH511U8Cupw %}

## Prerequisites

To code along with this article, you'll need the following tools and knowledge:

- Your preferred text editor or IDE.
- Python knowledge.
- HTML knowledge
- A web browser (Google Chrome is the recommended browser for PyScript).

## What is PyScript?

![Image pyscript logo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nhiaeq6akd6u4chuctfx.png)
 

[PyScript](https://pyscript.net/) is a Python front-end framework that lets users write Python applications in the web using an HTML interface.


It was created with the help of [Emscripten](https://emscripten.org/), [Pyodide](https://pyodide.org/en/stable/), [WASM](https://webassembly.org/), and other modern web technologies to provide the following capabilities:

- To provide a simple and easy-to-use API.
- To create a system of extendable and pluggable components.
- To achieve the aim "Programming for the 99 percent," support and expand standard HTML to read opinionated and dependable bespoke components.

![Image pyscript arch](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i4fee6o5lf3xo9bdo5a9.png)

In the last few decades, Python and complicated UI languages like contemporary HTML, CSS, and JavaScript have not functioned together. While traditional HTML, CSS, and JavaScript have a steep learning curve, Python lacks a simple mechanism for quickly packaging and delivering projects with beautiful UIs.

Allowing Python to use HTML, CSS, and JavaScript conventions solves not only those two issues, but also web application development, packaging, distribution, and deployment.

> PyScript isn't intended to replace JavaScript in the browser; rather, it's intended to provide additional flexibility and capability to Python developers, particularly data scientists.

## Why PyScript?

PyScript provides a programming language with consistent styling conventions, increased expressiveness, and simplicity of learning by including the following features:

- **Browser-based support:** PyScript makes Python and hosting possible without the use of servers or settings.

- **Bi-directional communication** between Python and JavaScript objects and namespaces is possible using PyScript.

- PyScript supports a **wide range of Python packages**, including Pandas, NumPy, and many others.

- **Flexibility of the framework:** PyScript is a flexible framework that allows developers to easily write extensible components in Python.

- PyScript's **environment management** feature allows authors to specify which files and packages should be included in their page code for it to run.

- **UI Development:** PyScript allows developers to quickly create UI components such as buttons and containers, among others.

## How to Get Started with PyScript

To get started with PyScript, add the relevant pyscript files to your HTML page. Let's use PyScript to create a simple "Hello World" page.



Let's create an `index.html` file and import the necessary PyScript files. These should go just before the closing `</head>` tag.

````html
<head>
   <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
   <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
   <title>PyScript</title>
</head>
```
Now that we've linked PyScript to the HTML file, we can print our "Hello World."

We can do this with the `<py-script>` tag. We can use the `<py-script>` tag to run multi-line Python scripts in the browser. The tag should be in the middle of the `<body>` tags.

```html
<body>
   <py-script> print("Hello, World!") </py-script>
</body>
```


You should see the following in your browser:


![Image hello world output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9fig0ypc2rnexr2mdlzw.png)


The PyScript framework allows you to perform a variety of actions. Let's take a look at a few of them right now.


**Python output in HTML tags**

When using PyScript, you may want to pass variables from your Python code to HTML. To accomplish this, use the `write` method from the `pyscript` module within the `<py-script>` element. The id attribute can be used to pass strings that are displayed as ordinary text.


The write method takes two parameters: the `id` value and the variable to be supplied.

Here's a simple pyScript code that uses Python's datetime module to output today's date.

```html 
<html>
<head>
    <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
    <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
    <b>
        <p>Today is <u><label id='today'></label></u></p>
    </b>
    <py-script>
        import datetime as dt
        pyscript.write('today', dt.date.today().strftime('%A %B %d, %Y'))
    </py-script>
</body>
</html>
```


And the output:

![Image todays's date output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k3fsto9mch5hxtx0v7ux.png)
 





**REPL in browser**

PyScript provides a web-based interface for running Python code.

PyScript uses the `<py-repl>` tag to do this. The `<py-repl>` tag includes a REPL component, which works as a code editor and allows you to write executable code inline.

```html
<html>
  <head>
    <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
    <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
  </head>
  <py-repl id="my-repl" auto-generate=true> </py-repl>
</html> 
```

![Image repl output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v4nm3enek2xmk6dnvlpn.png)
 
**Import Files, Modules, and Libraries**

One of PyScript's advantages is its adaptability. Local files, built-in modules, and third-party libraries can all be imported into PyScript. The `<py-env>` tag is used to do this. This tag is used to declare the required dependencies.

You can put the code in a `.py` file for local Python files on your system, and the paths to local modules are specified in the paths: key in the `<py-env>` tag.

Let's create a Python file `random_number.py` that returns a number between 1 and 10.

```python
from random import randint

def generate_random_number():
    x = randint(0,10)
    return x
```

The <py-env> element will then be used to import the Python file into the HTML. This tag should be placed in the `<head>` tag.


```html
<html>
    <head>
      <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
      <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
      <py-env>
        - paths:
          - ./random_number.py
      </py-env>
    </head>

  <body>
    <h1>Let's print random numbers</h1>
    <b>Your random number is  <label id="lucky"></label></b>
    <py-script>
      from random_number import generate_random_number
      pyscript.write('lucky', generate_random_number())
    </py-script>
  </body>
</html>
```

Here's the output:

![Image random number output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/raf524yosgywvko6i9yt.png)

PyScript also supports third-party libraries that are not included in the standard library.

Here's a simple scatter plot using PyScript:

```html
<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>
    <py-script>
        import matplotlib.pyplot as plt
        import numpy as np
        
        x = np.random.randn(500)
        y = np.random.randn(500)
        
        fig, ax = plt.subplots()
        ax.scatter(x, y)
        fig
    </py-script>
</body>
</html>
```

And the Output:

![Image scatter plot output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6mrx8r126gmye5mwlhbh.png)
 

**Configure metadata**

Using the <py-config> tag, you can set and customize general metadata about your PyScript application. This tag can be used in the following format:

```html
<py-config>
  - autoclose_loader: false
  - runtimes:
    -
      src: "https://cdn.jsdelivr.net/pyodide/v0.20.0/full/pyodide.js"
      name: pyodide-0.20
      lang: python
</py-config>
```

These are the optional values provided by the py-config tag. They are as follows:

- **autoclose_loader (boolean):**  PyScript will not close the loading splash screen if autoclose loader (boolean) is set to false.

- **name (string):** The application's name.

- **version (string):** The application's version.

- **runtimes (List of Runtimes):** This is a list of runtime settings with the fields src, name, and lang.


## Conclusion

You learnt what PyScript is and how to use it in HTML pages to run Python code in the browser. You also learned about the many operations and functionalities that PyScript can perform.

PyScript makes it easier to run and perform Python operations on the web, which was previously difficult. This is an incredible tool for anyone interested in using Python on the web.

PyScript is still in its infancy and is undergoing extensive development. It is still in the alpha stage and has known faults such as slow loading times, which can make it unusable. As a result, you shouldn't use it in production just yet because there will very certainly be many breaking changes.

## References

- [The PyScript official website](https://pyscript.net/)

- [Anaconda blog](https://www.anaconda.com/blog/pyscript-python-in-the-browser)

- [PyScript source code](https://github.com/pyscript/pyscript)

- [Guide on getting started with PyScript](https://github.com/pyscript/pyscript/blob/main/docs/tutorials/getting-started.md)