SoFunction
Updated on 2024-11-19

Running Python Scripts in a Web Browser PyScript Dissection

main body (of a book)

PyScript lets you run Python scripts directly in your browser, side-by-side with JavaScript, for two-way interaction between your code and web pages.

Created by Anaconda, PyScript is an experimental but promising new technology that enables the Python runtime to be used as a scripting language in browsers that support WebAssembly.

Every modern, commonly used browser now supportsWebAssembly, which is a high-speed runtime standard that many languages (such as C, C++, and Rust) can compile.The reference implementation of Python is written in C. An early projectPyodideA WebAssembly port of the Python runtime is provided.

Also at InfoWorld: The Rise of WebAssembly

However.PyScriptThe goal is to provide a complete browser environment that runs Python as a web scripting language. It builds on top of Pyodide, but adds or enhances features such as importing modules from standard libraries, using third-party imports, configuring bi-directional interaction with the Document Object Model (DOM), and doing many other things that are useful in the world of Python and JavaScript.

For now, PyScript remains a prototype and experimental project.Anaconda does not recommend using it in production. But curious users can try out some examples on the PyScript website and build experimental Python+JavaScript applications in the browser using the available components.

In this post, we'll take a tour of the basics of PyScript and see how it allows Python and JavaScript to interact.

Programming with PyScript

At the heart of PyScript is a single JavaScript include that you can add to a web page. This include loads the basic PyScript runtime and automatically adds support for custom tags used in PyScript.

Here is a simple example of a PyScript "hello, world" project.

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="/alpha/" rel="external nofollow"  rel="external nofollow"  />
        <script defer src="/unstable/"></script>
    </head>
    <body>
<py-script output="out">
print("Hello world")
</py-script>
<div ></div>
    </body>
</html>

head Documentationscript tags are loaded with core PyScript functionality. The stylesheet is optional, but useful. Among other things, it inserts notifications to the user about what the page is doing when it loads - loading the Python runtime, initializing, etc.

Python code is included in the customizedpy-script in the tags. Note that the code should be formatted according to Python's indentation conventions, or it will not work properly. If you're using an editor that automatically reformats HTML, be aware of this; it may mess up thepy-script block to make it inoperable.

Once the PyScript component is loaded, any Python code is evaluated. If the script in the tag is written tostdout (e.g.print) statement, you can make it work by supplying aoutput attribute to indicate where on the page to display the output. In this example, the script'sstdout Being directed to the ID of the"out" (used form a nominal expression)div

If you save it to a file and open it in a web browser, you'll first see a "loading" indicator and a pause as the browser gets the PyScript runtime and sets it up. That runtime should remain cached for future loads, but it will still take some time to activate. After that.Hello world It should appear on the page.

Standard library import

Scripts that simply use Python's built-in programs are only marginally useful.Python's standard library is available in PyScript, just as you would use it in regular Python: simplyimport and start working. The standard library import should just work in PyScript.

If you want to modify the script block above to display the current time, you don't need to do it in a different way than traditional Python.

import datetime
print ("Current date and time:",    ().strftime("%Y/%m/%d %H:%M:%S"))

Using libraries from PyPI

What if we want to install a package from PyPI and use it?PyScript has another tab.py-env , which specifies the third-party packages that need to be installed. Let's replace the original script'spy-script Blocks.

<py-env>
- humanize
</py-env>
<py-script output="out">
from datetime import datetime
import humanize
now_int = int((()))
now_fmt = (now_int)
print("It has been", now_fmt, "seconds since the epoch.")
</py-script>

py-env block lets us list the packages we want to add, just as we did in the Python project's file that lists them. We can then import and use them as we would any other Python package. In this example, we're using a package calledhumanize of third-party software packages to make the digital output easier to read.

Note that not all packages from PyPI install and run as expected. For example.requests Requires access to network components that are not yet supported. (A possible workaround for this problem is to use the It's beennative support). But pure Python packages such ashumanize The examples provided by Anaconda use packages such asnumpy,pandas,bokeh, ormatplotlib , can also be run.

Local Import

For another common scenario, suppose you want to import from other Python scripts that are in the same directory tree as your web page. Using imports makes it easier to move more Python logic out of the web page itself, where it gets mixed up with your presentation and can become unwieldy.

Typically, Python uses other filesystem.py The existence of a file serves as an indication that it can be imported.PyScript doesn't work this way, so you need to specify which files can be used as importable modules.

Let's say you have a file named in a directory on your web server, and you want to place next to it a page named Python file. This way, your in-page scripts can just beimport main and you can confine most of the Python logic to the actual.py Documentation.

in yourpy-env block to specify the Python file you want to import.

- paths:`` - ./

This will allow The web server directory is the same as the web page itself, and can be used in conjunction with theimport main Imported together.

One important thing to remember. You can't do this kind of import for web pages that you launch locally in your browser. This is due to limitations in file system access by the WebAssembly runtime and the browser itself. Instead, you'll need to host these pages on a web server to provide both the pages and the.py Documentation.

[Also at InfoWorld: 4 keys to writing modern Python in 2022]

REPL Tags

Python users should familiarize themselves withJupyter Notebook, which is an in-browser, real-time coding environment for Python, often used for math and statistics.PyScript provides a primitive building block for such an environment, thepy-repl Tags.

py-repl Generating an input field on a web page functions like a very basic Jupyter notebook environment. Here's an example from Anaconda's own demo.

<!DOCTYPE html>
<html lang="en">
  <head>
    <link rel="stylesheet" href="/alpha/" rel="external nofollow"  rel="external nofollow"  />
    <script defer src="/alpha/"></script>
  </head>
  <body>
    <h1><b>pyscript REPL</b></h1>
    Tip: press Shift-ENTER to evaluate a cell
    <div>
      <py-repl  auto-generate="true"> </py-repl>
    </div>
  </body>
</html>

Run this code and you'll see an input field that works similar to Python's REPL.

Currently, there are very few documented ways to customize REPL tags. For example, if you want to programmatically access the contents of a cell or its results, there is no clear documentation on how to do this.

IDG

PyScript's Jupyter-like REPL component lets you run Python interactively in a page, although it's not yet very flexible or configurable.

Interacting with JavaScript Event Listeners

Because PyScript is based onpyodide so it uses thepyodide mechanism to interact with the DOM. For example, if we wanted to get the value of an input box on a web page and use it in our Python code, we would do so.

<input >
<py-script>
from js import document, console
from pyodide import create_proxy
def _eventlog(e):
    (f"Input value: {}")
eventlog = create_proxy(_eventlog)
("txt").addEventListener("input", eventlog)
</py-script>

js library provides a Python interface to many common JavaScript entities, such as thedocument cap (a poem)console objects. Their behavior in PyScript is almost identical to their behavior in JavaScript.pyodide hit the nail on the headcreate_proxy function allows us to take a Python function object and generate a JavaScript interface for it, so it can be used as ainput event listener for the box.input Any keystrokes in the box are logged to the console, but they can also be processed on the Python side.

Above is the web browser to run Python script PyScript analysis of the details, more information about the browser to run Python PyScript please pay attention to my other related articles!