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
-
Gnome 47.1 Released with a Few Fixes
The latest release of the Gnome desktop is all about fixing a few nagging issues and not about bringing new features into the mix.
-
System76 Unveils an Ampere-Powered Thelio Desktop
If you're looking for a new desktop system for developing autonomous driving and software-defined vehicle solutions. System76 has you covered.
-
VirtualBox 7.1.4 Includes Initial Support for Linux kernel 6.12
The latest version of VirtualBox has arrived and it not only adds initial support for kernel 6.12 but another feature that will make using the virtual machine tool much easier.
-
New Slimbook EVO with Raw AMD Ryzen Power
If you're looking for serious power in a 14" ultrabook that is powered by Linux, Slimbook has just the thing for you.
-
The Gnome Foundation Struggling to Stay Afloat
The foundation behind the Gnome desktop environment is having to go through some serious belt-tightening due to continued financial problems.
-
Thousands of Linux Servers Infected with Stealth Malware Since 2021
Perfctl is capable of remaining undetected, which makes it dangerous and hard to mitigate.
-
Halcyon Creates Anti-Ransomware Protection for Linux
As more Linux systems are targeted by ransomware, Halcyon is stepping up its protection.
-
Valve and Arch Linux Announce Collaboration
Valve and Arch have come together for two projects that will have a serious impact on the Linux distribution.
-
Hacker Successfully Runs Linux on a CPU from the Early ‘70s
From the office of "Look what I can do," Dmitry Grinberg was able to get Linux running on a processor that was created in 1971.
-
OSI and LPI Form Strategic Alliance
With a goal of strengthening Linux and open source communities, this new alliance aims to nurture the growth of more highly skilled professionals.