New PyScript project lets you run Python programs in the browser
The new PyScript project lets you embed Python programs directly into HTML pages and run them in the browser without any server-based requirements.
The project was announced this weekend at PyCon US 2022 and acts as a wrapper around the Pyodide project, which loads the CPython interpreter as a WebAssembly browser module.
“PyScript is a framework that allows users to create rich Python applications in the browser using a mixture of Python with standard HTML.” explains Anaconda in a recent blog post.
“PyScript aims to provide users with a first-class programming language that has consistent style rules, is more expressive, and is easier to learn.”
While the Pyodide project previously allowed you to run Python in the browser, the syntax takes some getting used to and it’s not as elegant as just writing a Python program and pasting it into your HTML page.
However, Python acts as a wrapper, allowing you to embed Python code directly between
py-script tags and have it executed automatically by Pyodide.
For example, the following shows a small Hello World example using PyScript and running it directly in the browser. Notice how the
pyscript.write() The function allows you to output data directly into an HTML element.
Developers can also extend PyScript pages via additional Python packages integrated with Pyodide or via those stored on the local file system. from Python GETTING STARTED.md The file provides documentation on how to import packages into your code.
In addition to executing code embedded in HTML, it is also possible to add a code editor directly to an HTML page using the
py-repl tag so you can enter code and run it as shown below.
Using the editor makes it easy to test code on the fly and see what will and won’t work with PyScript.
To get started with PyScript, you can visit their GitHub project pagewhich also includes many code samples.