PyScript
A framework for running Python scripts in a web browser.
PyScript is a framework for running Python scripts in a web browser, presented by Peter Wang at a Python developer conference in June 2022. It is primarily developed by Anaconda, Inc. and allows Python to be used for frontend web development alongside or in place of JavaScript.
Quick Facts
- Developer
- property
- reference
- P178
- Latest release version
- property, reference, edit, P348
- Operating system
- property
- reference
- P306
- License
- property
- reference
- P275
- Influenced by
- property
- reference
- P737
Facts from the source article.
Usage
PyScript enables Python scripts, which normally execute on a server, to run in a web browser, allowing the same language for both backend and frontend development. It is a TypeScript library loaded by the web page that interprets embedded Python scripts, with no dependencies beyond its JavaScript library and CSS rules. PyScript can replace JavaScript or operate alongside it, enabling cross-calling between the two. Its advantage lies in the extensive Python libraries available for web pages, which must be installed on the server. For instance, graphics libraries for editing digital images allow client-side processing of image data instead of sending it to the server, and libraries for creating graphs and diagrams are also usable. Python has historically had little support for pure front-end development, and PyScript aims to close this gap. To execute Python scripts in a browser, a Python runtime environment is needed; PyScript can work with various runtimes but defaults to Pyodide, a port of CPython to WebAssembly. Many well-known Python packages have been ported to WebAssembly for use with PyScript. Pyodide was developed in 2018 by Michael Droettboom at the Mozilla Foundation.
Examples
The first example imports packages for output control, date management, and event handling. Each time a button is clicked, the current date and time are displayed in a new line. The code uses from pyscript import when, display and from datetime import datetime, with a @when("click", "#btnTime") decorator on a click handler that calls display with a formatted datetime string. As an alternative to the <py-script> element, the <script type="py"> element can be used, though the new notation is recommended. PyScript also supports a command prompt interface by adding the terminal attribute to the <py-script> or <script> element; for input, the worker attribute must also be specified. Earlier versions used the <py-terminal> element. Another example creates a bar chart using matplotlib, loading the package in a <py-config> block. The code imports matplotlib.pyplot and pyscript.display, creates a bar chart with fruit categories and popularity values, and displays it via display(fig, target="mpl").
More in Python
Spotted an error? Know more?
Reader corrections go straight into our review queue. Suggest an edit · How this site is sourced
