Using Python in the browser
PyScript with JavaScript Libraries
In many cases you'll want to use JavaScript libraries along with PyScript. For example, you might want to include JavaScript prompts or alert messages for your page. To access a JavaScript library, add the line:
from js import some_library
Listing 3 shows the code to import the alert and prompt libraries, then prompts the user for their name, and finally displays an alert message with the entered name (Figure 6).
Listing 3
JavaScript Libraries with PyScript
<py-script> # Use a JS library to show a prompt and alert message from js import alert, prompt # Ask your name, then show it back name = prompt("What's your name?", "Anonymous") alert(f"Hi:, {name}!") </py-script>
Reading and Plotting a Local CSV File
For a final, more challenging example, I'll use PyScript to read a local CSV file into a pandas dataframe and then use Matplotlib to plot a bar chart (Figure 7).
For security reasons, web browsers cannot access local files without the user's authorization. To allow PyScript to access a local file, you need to do three key things. To start, you need to configure a page with an <input type="file">
tag. To call a file-picker dialog with a CSV filter, enter:
<input type="file" id="myfile" name="myfile" accept=".csv">
Next, you must define an event listener to catch a change in the <input>
file. For this step, two libraries need to be imported, and an event listener needs to be configured as shown in Listing 4.
Listing 4
Defining an Event Listener
from js import document from pyodide.ffi.wrappers import add_event_listener # Set the listener to look for a file name change e = document.getElementById("myfile") add_event_listener(e, "change", process_file)
Finally, you need to import the JavaScript FileReader
and the PyScript asyncio
libraries as follows:
from js import FileReader import asyncio
The FileReader
object is used to read in the CSV file's content. The asyncio
library creates background event processing to allow functions to complete successfully without timing or delay issues.
Listing 5 shows the full code for reading and plotting a local CSV file. In Listing 5, pay particular attention to:
- defining a
<py-config>
section for the pandas and Matplotlib (PyPI) libraries (lines 9-11) and - creating an
async
function (process_file(event)
).
Note, the async
function is launched from the add_event_listener
(line 51) when the user selects a file.
Listing 5
PyScript CSV File to Bar Chart
01 <!DOCTYPE html> 02 <html lang="en"> 03 <head> 04 <title>Pyscript CSV to Plot</title> 05 <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" /> 06 <script defer src="https://pyscript.net/latest/pyscript.js"></script> 07 <title>Local CSV File to Matplotlib Chart</title> 08 <!-- Include the Pandas and Matplotlib packages --> 09 <py-config> 10 packages = [ "pandas", "matplotlib" ] 11 </py-config> 12 </head> 13 <body> 14 15 <h1>Pyscript: Input Local CSV File and Create a Bar Chart</h1> 16 <label for="myfile">Select a CSV file to graph:</label> 17 <input type="file" id="myfile" name="myfile" accept=".csv"><br> 18 19 <div id="lineplot"> </div> 20 <pre id="print_output"> </pre> 21 <py-script output="print_output"> 22 import pandas as pd 23 import matplotlib.pyplot as plt 24 from io import StringIO 25 import asyncio 26 from js import document, FileReader 27 from pyodide.ffi.wrappers import add_event_listener 28 29 # Process a new user selected CSV file 30 async def process_file(event): 31 fileList = event.target.files.to_py() 32 for f in fileList: 33 data = await f.text() 34 # the CSV file is read as large string 35 # use StringIO to pass info into Panda dataframe 36 csvdata = StringIO(data) 37 df = pd.DataFrame(pd.read_csv(csvdata, sep=",")) 38 print("DataFrame of:", f.name, "\n",df) 39 40 # create a Matplotlib figure with headings and labels 41 fig, ax = plt.subplots(figsize=(16,4)) 42 plt.bar(df.iloc[:,0], df.iloc[:,1]) 43 plt.title(f.name) 44 plt.ylabel(df.columns[1]) 45 plt.xlabel(df.columns[0]) 46 # Write Mathplot figure to div tag 47 pyscript.write('lineplot',fig) 48 49 # Set the listener to look for a file name change 50 e = document.getElementById("myfile") 51 add_event_listener(e, "change", process_file) 52 53 </py-script> 54 </body> 55 </html>
The CSV file is read into a variable (line 34), and then the StringIO
function allows the data to be passed into a pandas dataframe (lines 36 and 37). Line 38 outputs the dataframe to a py-terminal
element:
print("DataFrame of:", f.name, "\n",df)
This example only presents bar charts for the first two rows of data (lines 42-45), but the code would be modified to do line plots for multiple rows of data. Line 47 sends the Matplotlib figure to the page's <div id="lineplot">
element:
pyscript.write('lineplot',fig)
Although somewhat complex, this example only took 30 lines of Python code. Good future projects could include adding options for sorting, grouping, and customized plots. It's important to note that PyScript can also be used to save files to a local machine.
Summary
Using Python libraries such as pandas, SymPy, or Matplotlib on a client page can be a very useful feature. It's also nice that these PyScript pages don't require Python on the client machine.
While working with PyScript, I found two issues. The call-up is very slow (especially compared to Brython pages). In addition, I often got tripped up with Python indentation when I was cutting and pasting code. Overall, however, I was very impressed with PyScript, and I look forward to seeing where the project goes.
Infos
- Brython: https://brython.info/
- PyScript: https://pyscript.net/
« Previous 1 2
Buy this article as PDF
(incl. VAT)
Buy Linux Magazine
Subscribe to our Linux Newsletters
Find Linux and Open Source Jobs
Subscribe to our ADMIN Newsletters
Support Our Work
Linux Magazine content is made possible with support from readers like you. Please consider contributing when you’ve found an article to be beneficial.
News
-
Rhino Linux Announces Latest "Quick Update"
If you prefer your Linux distribution to be of the rolling type, Rhino Linux delivers a beautiful and reliable experience.
-
Plasma Desktop Will Soon Ask for Donations
The next iteration of Plasma has reached the soft feature freeze for the 6.2 version and includes a feature that could be divisive.
-
Linux Market Share Hits New High
For the first time, the Linux market share has reached a new high for desktops, and the trend looks like it will continue.
-
LibreOffice 24.8 Delivers New Features
LibreOffice is often considered the de facto standard office suite for the Linux operating system.
-
Deepin 23 Offers Wayland Support and New AI Tool
Deepin has been considered one of the most beautiful desktop operating systems for a long time and the arrival of version 23 has bolstered that reputation.
-
CachyOS Adds Support for System76's COSMIC Desktop
The August 2024 release of CachyOS includes support for the COSMIC desktop as well as some important bits for video.
-
Linux Foundation Adopts OMI to Foster Ethical LLMs
The Open Model Initiative hopes to create community LLMs that rival proprietary models but avoid restrictive licensing that limits usage.
-
Ubuntu 24.10 to Include the Latest Linux Kernel
Ubuntu users have grown accustomed to their favorite distribution shipping with a kernel that's not quite as up-to-date as other distros but that changes with 24.10.
-
Plasma Desktop 6.1.4 Release Includes Improvements and Bug Fixes
The latest release from the KDE team improves the KWin window and composite managers and plenty of fixes.
-
Manjaro Team Tests Immutable Version of its Arch-Based Distribution
If you're a fan of immutable operating systems, you'll be thrilled to know that the Manjaro team is working on an immutable spin that is now available for testing.