Ronnie Atuhaire
Ronnie Atuhaire's Blog

Ronnie Atuhaire's Blog

Run Python Directly In HTML With PyScript

Run Python Directly In HTML With PyScript

PyScript Vs Javascript

Ronnie Atuhaire's photo
Ronnie Atuhaire
May 19, 2022

7 min read

Subscribe to my newsletter and never miss my upcoming articles

Table of contents

  • What is PyScript?
  • Introduction to PyScript
  • Downloading the zip (Clone)
  • Is PyScript a programming language?
  • Will It Crush Javascript?
  • Note
  • Summary
  • Notes & Resources
  • Conclusion

Imagine writing your favourite programming language everywhere and not being limited by the terminal. Yes, you can now write Python code in the browser HTML and render it with PyScript and it is quite easier than you think.

What is PyScript?

PyScript is a framework that allows users to create rich Python applications in the browser using HTML's interface and the power of Pyodide, WASM and modern web technologies.

image.png

Pyodide is a port of CPython to WebAssembly/Emscripten. Pyodide makes it possible to install and run Python packages in the browser. Visit the REPL here to play with it.

The PyScript framework provides users at every experience level with access to an expressive, easy-to-learn tool with countless applications.

PyScript is a Pythonic alternative to Scratch, JSFiddle, and other "easy to use" programming frameworks, with the goal of making the web a friendly, hackable place where anyone can author interesting and interactive applications.

Introduction to PyScript

To get started see the getting started tutorial but let's see how to use the three most useful tags now when using PyScript.

I will basically do a Hello World Program from PyScript today, and I will be building small web apps, some scraping with it and other related PyScript tutorials in the near future as it gets better.

<py-script>

It can be used to define python code that is executable within the web page. The element itself is not rendered to the page and is only used to add logic.

<!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>Hello PyScript</title>
</head>
<body>
    <py-script>
        print('Hello PyScript')

        def hello():
            return 'Hello PyScript from a function'

        hello()
    </py-script>
</body>
</html>

So we basically added it in order to write our Python with py-script tags;

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

The defer in the script tag is a Boolean value, used to indicate that script is executed after the document has been parsed. It works with external scripts.

As you can see from my file, indentation is really important even when writing Python in HTML.

To run the above file, you can either click on it and load it with Chrome but I would recommend using a live server (VS Code Extension) or easily serve it with Python's http.server module by running;

python -m http.server

Python http.server module can be invoked directly using the -m switch of the interpreter. This serves files relative to the current directory but you might have to refresh for changes, unlike Live Server.

Yeah, it is really clunky and slow...

image.png

Finallly ... image.png

What if the codebase becomes too big, you won't write all that in the py-script tags, so you can now create a Python file in the same root folder.

So you can add it in the src attribute like this;

<py-script src="index.py"></py-script>

So our new changes;

image.png

What if you have modules and you want to be able to use some of those. If you are working with built-in python libraries is simple, you just import them as you would usually do in python.

So let's try the math library. Add another py-script tag for this;

<py-script>
        # Standard Python Libraries
        import math

        squares = [math.sqrt(i) for i in [4,16,36,64]]  
        print(squares)
</py-script>

Our new output;

image.png

<py-env>

What if we want to use external modules. This introduces us to the second PyScript tag which can be declared in the tag and a list of these libraries is outlined.

<py-env>
        - numpy
</py-env>

Create another py-script tag in the body;

<py-script>
        # External Supported Libraries
        import numpy as np

        arr = np.array([2,4,6,8])
        print("Square Value of arr : ", np.square(arr))
</py-script>

Output;

image.png

Obviously, you can add some styling with another file or bootstrap to have them representable and that is my little challenge to you if you are a front-end dev.

<py-repl>

This creates a REPL component that is rendered to the page as a code editor and allows users to write executable code.

Just add this under our py-script tags;

<py-script>
        print("Interactive Shell;")
</py-script>

<py-repl> </py-repl>

Then in our interactive shell after loading the server, add this in the REPL and execute or hit Shift + Enter.

import math
math.sqrt(4)

Output;

image.png

Visit this repo for the full code of this introduction .

Downloading the zip (Clone)

Please make sure to move the extracted files to the root of your main HTML file if you are going to use the offline version after compiling it with Node.

There is currently no proper documentation around this but you can stay posted by watching the repo or stay updated here.

Is PyScript a programming language?

To me, it is a JavaScript-Python framework that allows users to create applications in the browser using a mix of Python and standard HTML.

image.png

Developed by the Anaconda team, the projects ultimate goal is to allow a much wider audience (for example, front-end developers) to benefit from the power of Python and its various libraries (statistical, ML/DL, etc.).

According to GitHub metrics, the current repo by the time of writing is 32.5% HTML, 31% Javascript, 19.3% Typescript & only 15.5% Python because we all know Python was not initially designed for the web.

Will It Crush Javascript?

I know you are still wondering if this new beautiful Python-Javascript framework will replace Javascript. I think nope, Javascript is a fully fledged programming language that is stable and more performant than just a mere framework that actually sits on top of it.

It might not as of now because it is still in an Alpha stage and can only get to compete with Django, and Flask because you do not need Jinja, templates anymore.

image.png

Maybe Django developers will find this way easier, especially when it is enhanced and improved significantly over time and I can't wait for that time personally.

Data scientists have already embraced this tool and those who wish to share the results of their research can do it more easily now. Maybe we can see some new fields of front-end development coming up.

Note

This is an extremely experimental project, so expect things to break and when using the CDN version, it can take some significant time to load the runtime!

It has been only tested on Chrome at the moment and may not fully support other browsers.

The alpha release of PyScript can be found on PyScript website. The code is available here. For more examples visit this folder.

Summary

It is really promising, but it can potentially open quite a lot of new other security issues which I believe will be addressed gradually when we get the first stable version.

image.png

There are limits to the libraries you can use currently, please visit Pyodide Supported modules for more information.

I am personally curious to see where it will lead us too and I believe its future is so bright with over 10k + Stargazers by the time of writing this post and it is barely a few months out.

I forked the project a few weeks ago and I would personally start contributing to it because I am excited to see its future and usefulness come to life.

Notes & Resources

PyScript: Python in the Browser - Anaconda Article
PyScript Official Website
PyScript Official Repo
Pyodide

Conclusion

Once again, hope you learned something today from my little closet.

Please consider subscribing or following me for related content, especially about Tech, Python & General Programming.

You can show extra love by buying me a coffee to support this free content and I am also open to partnerships, technical writing roles, collaborations and Python-related training or roles.

Buy Ronnie A Coffee You can also follow me on Twitter : Waiting for you!
Share this