Introducing PyScript - How to Run Python in Your Browser

Introducing PyScript - How to Run Python in Your Browser

Is Python the new JavaScript now? Well, no, but you can still do cool things.

Anaconda’s CEO Peter Wang revealed something pretty interesting during PyCon US 2022. It’s PyScript - a JavaScript framework that allows you to create Python applications in the browser. That’s right, you can now embed Python code directly in HTML files, just as any JavaScript developer would do.

The idea behind PyScript is simple - data scientists can create websites around their models in their favorite language, provided they have fundamental HTML knowledge. HTML is kind of like SQL in one area - everyone knows it.

Will PyScript live up to its hype? Only time will tell. Today, I’ll show you two basic examples that will get you started with PyScript in minutes. Let me know if you want more advanced topics covered, such as machine learning and handling user input.

Don’t feel like reading? Watch my video instead:


What is PyScript and Why Should You Care?

PyScript is a system for interleaving Python in HTML (like PHP), according to Anaconda Cloud. This means you can write and run Python code in HTML, call JavaScript libraries, and handle pretty much anything web-development-related.

For data scientists, this means you can now create web applications around your data products. Everyone has access to a web browser, which makes the web an easier platform to get into than, let’s say, mobile.

Also, you don’t have to worry about deployment, as everything happens in the browser. You can share your models and dashboards as an HTML file, which will run the code whenever someone opens it in the web browser. Neat!

PyScript is built on Pyodide, which is a port of CPython to WebAssembly/Emscripten:

Image 1 - PyScript tech stack (source: https://anaconda.cloud/pyscript-python-in-the-browser)

Image 1 - PyScript tech stack (source: https://anaconda.cloud/pyscript-python-in-the-browser)

If you’re wondering, WebAssembly is a technology that makes it possible to write websites in Python. It’s a low-level assembly-like language with a compact binary format that runs with near-native performance and provides languages with a compilation target so they can run on the web, according to Mozilla.

But how can you actually use PyScript? Let’s answer that next.


How to Use PyScript

You can download the alpha release of PyScript on pyscript.net. We won’t download anything today. Instead, we’ll embed one stylesheet and one script in our HTML file. For reference, all HTML files that use PyScript must have a link to these:

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

PyScript allows you to write Python in HTML using the following components:

  • py-env - Defines the Python packages needed to run your Python code.
  • py-script - Part of the HTML file where you write your Python code.
  • py-repl - Creates a REPL component that evaluates the code user enters and displays the result.

We’ll deal with the first two today and save the last one for some other time.

Let’s see how you can write a simple Hello World program in PyScript.


PyScript Example #1 - Hello World

In Visual Studio Code, you can write an exclamation sign followed by a Tab to create a base HTML document structure. Inside the <head> tag, add the two links mentioned in the previous section.

The hello world example doesn’t require any external Python libraries, so we can ditch the <py-env> part altogether.

Before the closing </body> tag, open a new <py-script> tag that will contain the Python logic. Just note the indentation - it’s best to remove it completely. The formatting doesn’t look nice, but you’ll get an error otherwise.

What we’ll do is simple - print a hello world message and the current datetime info:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
    <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
    <title>First Python HTML app</title>
</head>
<body>
    <py-script>
from datetime import datetime 

print("Hello World!")
print(f"It's now {datetime.now()}")
    </py-script>
</body>
</html>

Open the HTML file in the browser - here’s what you’ll see in a couple of seconds:

Image 1 - Using Python in your browser - Hello World example (image by author)

Image 1 - Using Python in your browser - Hello World example (image by author)

And there it is! This would take you much more time to code in Flask, so PyScript is already showing itself as a viable alternative. Let’s go over a more complex example next.


PyScript Example #2 - Charts with Bokeh

You can’t create dashboards around your data products without charts. As of now, PyScript doesn&rsquo;t support Plotly, so we’ll have to settle for Matplotlib or Bokeh. Let’s go with the latter.

It requires a bunch of Bokeh JavaScript scripts, so just copy them from the snippet below.

This time, we rely on an external Python library - Bokeh - so make sure to specify it inside the <py-env> tag. I’ve copied the chart example from Bokeh gallery, just to make sure it works:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
    <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
    <script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-2.4.2.min.js"></script>
    <script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-gl-2.4.2.min.js"></script>
    <script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-widgets-2.4.2.min.js"></script>
    <script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-tables-2.4.2.min.js"></script>
    <script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-mathjax-2.4.2.min.js"></script>
    <title>Bokeh Example</title>
    <py-env>
    - bokeh
    </py-env>
</head>
<body>
    <h1>Bokeh Example in PyScript</h1>
    <div id="chart"></div>

    <py-script>
import json 
import pyodide 
from js import Bokeh, console, JSON
from bokeh.embed import json_item
from bokeh.plotting import figure
from bokeh.resources import CDN

fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
counts = [5, 3, 4, 2, 4, 6]
p = figure(x_range=fruits, height=350, title="Fruit Counts", toolbar_location=None, tools="")
p.vbar(x=fruits, top=counts, width=0.9)
p.xgrid.grid_line_color = None
p.y_range.start = 0
p_json = json.dumps(json_item(p, "chart"))
Bokeh.embed.embed_item(JSON.parse(p_json))
    </py-script>
</body>
</html>
Image 2 - Using Python in your browser - Bokeh example (image by author)

Image 2 - Using Python in your browser - Bokeh example (image by author)

And would you look at that! No need to code an entire web application just to show a simple chart. That’s where the power of PyScript lies.


Python for Web with PyScript - Where to Go from Here?

Long story short, PyScript simplifies the process of visually and interactively presenting your data product. Is it the best solution out there? No, at least not yet. Is it the easiest one to get started with? By a long shot.

I’m excited to see what the future PyScript releases will bring. As mentioned, it’s still in alpha, so a lot is expected to change in the future. Let me know if you’re interested in more advanced usage of PyScript - for example, creating a dashboard around a machine learning model.

What are your thoughts on PyScript? Do you plan to use it as a replacement for basic Python web apps? Let me know in the comment section below.

Stay connected