What is PyScript?#

The PyScript library provides HTML tags for embedding and executing Python code in your browser. PyScript is built using Pyodide, the WebAssembly port of CPython, which is compiled using Emscripten.

PyScript turns the browser into a code deployment tool that anyone can learn to use.

Example#

In this example, we are using the <py-script> HTML tag to generate a Matplotlib figure and display it as an image. Click Preview to see the rendered HTML.

To try it in your browser, copy the code below into an online HTML editor like W3School’s Tryit Editor, which allows you to modify, run, and even save your code. Watch the video below to see it in action!

<html>
    <head>
      <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
      <script defer src="https://pyscript.net/latest/pyscript.js"></script>
      <style>
        .pulse {
            animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
        }

        @keyframes pulse {
          0%, 100% {
            opacity: 1;
          }
          50% {
            opacity: .2;
          }
        }
      </style>
    </head>

  <body>
    <h1>Let's plot random numbers</h1>
    <div id="plot">
      <div class="pulse" >
        <p style='font-family: monospace sans-serif;'><big><big><big><big>&#10096;py&#10097;</big></big></big></big></p>
      </div>
    </div>

    <py-config>
      packages = [
       "numpy",
       "matplotlib"
      ]
    </py-config>

    <py-script>
import matplotlib.pyplot as plt
import numpy as np

x = np.random.randn(1000)
y = np.random.randn(1000)

fig, ax = plt.subplots()
ax.scatter(x, y)
pyscript.write('plot', fig)
    </py-script>
  </body>
</html>