Pyodide is a Python distribution based on WebAssembly and
Pyodide can be added to a project using the following CDN URL:
https://cdn.jsdelivr.net/pyodide/v0.25.0/full/pyodide.js
We can paste the above URL inside an HTML file using the <script>
tag to use Pyodide.
Once Pyodide is included using the above CDN, we can import various Python modules as well as execute Python code inside the HTML file. In the code given below, we import Python’s numpy
module in the browser:
Line 4: We include the Pyodide CDN to be able to use Pyodide.
Line 13: We use the loadPyodide()
function to asynchronously load the Python environment.
Line 15: We use the pyodide.loadPackage()
function to load the NumPy library in the browser.
Pyodide provides another function, pyodide.runPython()
, which takes a string of Python code and executes it inside the browser.
Line 4: We include the Pyodide CDN to be able to use Pyodide.
Line 13: We use the loadPyodide()
function to asynchronously load the Python environment.
Lines 15–18: We use the pyodide.runPython()
function and pass it a string of Python code. Inside the string, we first import the time
module and then create an f-string to display the current time using the time.strftime()
function. The pyodide.runPython()
function will execute this code and store the result in the variable pythonOutput
.
Line 21: We update the content of the HTML element with the ID output
to display the result stored in the variable pythonOutput
.
As we’ve seen, Pyodide provides an efficient way to run Python code inside a browser, allowing Python to have full access to the Web APIs. This makes it a go-to tool for developers looking to integrate Python seamlessly into web environments. Pyodide also has well-written and