Using Pyscript

Tue Aug 08 2023

Turns out you can run Python in the browser thanks to WASM and, specifically, PyScript. Let’s try it out and integrate it with Hugo!

So… this is the current date and time, computed by Python running in your browser!

- matplotlib - numpy - duckdb
from datetime import datetime
now = datetime.now()
print(now.strftime('%m/%d/%Y, %H:%M:%S'))
from datetime import datetime now = datetime.now() print(now.strftime('%m/%d/%Y, %H:%M:%S'))

Not only that! You can also use Python to generate plots, like this one:

import matplotlib.pyplot as plt from datetime import datetime now = datetime.now() fig, ax = plt.subplots() x = ['Last Year', 'This Year', 'Next Year', 'Future'] y = [10, 5, 9, 7] plt.plot(x, y) plt.xlabel('Date') plt.ylabel('Score') plt.title(f'Plot rendered at {now}') fig

Which comes from running this code:

import matplotlib.pyplot as plt
from datetime import datetime
now = datetime.now()
fig, ax = plt.subplots()
x = ['Last Year', 'This Year', 'Next Year', 'Future']
y = [10, 5, 9, 7]
plt.plot(x, y)
plt.xlabel('Date')
plt.ylabel('Score')
plt.title(f'Plot rendered at {now}')
fig

Using PyScript with Hugo

To use PyScript with Hugo, you need to add the following to your config.toml:

[markup.goldmark.renderer]
  unsafe= true

And then you can use PyScript like I’m doing in this post.

Jupyter REPL

You can also have an entire Jupyter REPL running in your browser, with the ability to run arbitrary Python code!

Go ahead and try this out (Shift+Enter to run):

from matplotlib import pyplot as plt
import numpy as np
x, y, scale = np.random.randn(3, 100)
fig, ax = plt.subplots()
ax.scatter(x=x, y=y, c=scale, s=np.abs(scale) * 500)
ax.set(title="Some random data!")
plt.show()
← Back to home!