PyScript: Python in the Browser
- With the new PyScript project, you can embed a Python code directly in your .html page content and code will execute within your browser without any server-based requirements. Read more about the project and its development here
- It's simple to use PyScript:
- 1) Include two scripts into your .html head content:
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" /> <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
- 2) Embedd a Python code in the py-script block - which will then render the code and show output on your page.
- I've decided to try it out, see examples below:
PyScript
<pyscript> print('Hello, World!') </pyscript>
Output from PyScript
Matplotlib Figure
- I wanted to test the plotting, so I decided to use code from my Distribution Analyser web application. You can read more about Distribution Analyser here, and play with it live here. One of the available options within the app is to generate Python code of the displayed distribution. I copied the code and made only 1 adjustment prior to embedding code within the PyScript: I had to change the last line from plt.show() to fig.
- In order to render Python code within .html, it is needed to place the code inside:
<div id="mpl"></div> <py-script output="mpl"> # Your plotting code here </py-script>
- If you are importing Python packages in your code, you should specify them in your .html document within head. In my case, I am using matplotlib, scipy and numpy, so I added these lines:
<py-env> - matplotlib - scipy - numpy </py-env>
PyScript
<div id="mpl"></div> <py-script output="mpl"> # -*- coding: utf-8 -*- # Generated using Distribution Analyser: # https://github.com/rdzudzar/DistributionAnalyser # 20220615_120246 # --- import matplotlib.pyplot as plt #v3.2.2 import numpy as np #v1.18.5 from scipy.stats import dweibull #v1.6.1 # Set random seed np.random.seed(1) # Function parameters scale=1.0 loc=0.0 c=2.07 # Generate evenly spaced numbers over a specified interval size = 400 x = np.linspace(dweibull.ppf(0.001, c, loc=loc, scale=scale ), dweibull.ppf(0.999, c, loc=loc, scale=scale ), size) # Freeze the distribution rv = dweibull(c, loc=loc, scale=scale) # Generate random numbers r = dweibull.rvs(c, loc=loc, scale=scale, size=size) # Make a plot fig, ax = plt.subplots(2, 1, gridspec_kw={'height_ratios': [9, 0.7]}) # Plot PDF, CDF and SF ax[0].plot(x, rv.pdf(x), linestyle='-', color='#3182bd', lw=3, label='PDF') ax[0].plot(x, rv.cdf(x), linestyle='-', color='k', lw=3, label='CDF') ax[0].plot(x, rv.sf(x), linestyle='-', color='#df65b0', lw=3, label='SF') # Plot Histogram ax[0].hist(r, density=True, bins=20, color='lightgrey', edgecolor='k', label='Sample') # Plot Boxplot bp = ax[1].boxplot(r, patch_artist=True, vert=False, notch=False, showfliers=False, ) # Boxplot aestetic for median in bp['medians']: median.set(color ='red', linewidth = 2) for patch in bp['boxes']: patch.set(facecolor='white') # Set legend ax[0].legend(bbox_to_anchor=(0,1.1,1,0.2), loc="center", borderaxespad=0, ncol=2) # Set Figure aestetics ax[0].spines['top'].set_visible(False) ax[0].spines['right'].set_visible(False) ax[0].set_title('Distribution: dweibull') ax[1].set_xlim(ax[0].get_xlim()) ax[1].set_ylim(0.9, 1.1) ax[1].spines['left'].set_visible(False) ax[1].spines['top'].set_visible(False) ax[1].spines['right'].set_visible(False) ax[1].set_yticklabels([]) ax[1].set_yticks([]) ax[1].set_xlabel('X value') ax[0].set_ylabel('Density') fig </py-script>
Output from PyScript
Colormap
- Here is an example of a Colormap. The colormap code is generated with the Color Extractor web application. You can access web app here..
PyScript
<div id="plot"></div> <py-script output="plot"> # -*- coding: utf-8 -*- # Generated using Color Extractor: # https://github.com/rdzudzar/ColorExtractor # 20220615_130653 # --- import matplotlib # v3.4.3 import matplotlib.pyplot as plt import numpy as np #v1.20.3 # Add #colors and create colormap created_cmap = matplotlib.colors.LinearSegmentedColormap.from_list("mycmap", ['#075b7f', '#f5ebcf', '#cb2fce']) # Register name of your colormap plt.register_cmap("mycmap", created_cmap) # Get colors from the cmap x = np.linspace(0, 1, 256)[None, :] # See how colormap looks like fig, ax = plt.subplots(figsize=(7,1.32)) ax.imshow(x, aspect='auto', cmap = "mycmap") # Turn off the X and Y axes ax.set_axis_off() ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) fig </py-script>
Output from PyScript
A Python REPL (Read Eval Print Loop)
- With PyScript, you can embedd a REPL component on your webpage and it will behave as a code editor, which will allow visitors to write executable code. Try it below! You can press play button or Shift+Enter to execute a Python code, e.g.: print("It works!").
PyScript Code
<div> <py-repl id="my-repl" auto-generate="true"> </py-repl> </div>
Output:
Instead of Conclusions
- It's new! It works!
- Yes, it's a bit slow, but have in mind it's still in development. You can find more PyScript examples on their GitHub page, and test them out on their live web page.