Python in the browser—Pyodide
Pyodide is a Python distribution based on WebAssembly and
Getting started
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.
Importing Python modules in a browser
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:
Code explanation
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.
Executing Python code in a browser
Pyodide provides another function, pyodide.runPython(), which takes a string of Python code and executes it inside the browser.
Code explanation
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 thetimemodule and then create an f-string to display the current time using thetime.strftime()function. Thepyodide.runPython()function will execute this code and store the result in the variablepythonOutput.Line 21: We update the content of the HTML element with the ID
outputto display the result stored in the variablepythonOutput.
Conclusion
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
Free Resources