Python in the browser—Pyodide

Pyodide is a Python distribution based on WebAssembly and EmscriptenEmscripten is a compiler that converts C/C++ code into WebAssembly, enabling developers to run native applications on the web. and is designed to run Python in the browser. It allows installing and running any Python package, having a wheel available on PyPIPyPI stands for Python Package Index. It is a collection of software packages created and distributed by the Python community., in the browser.

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:

  • HTML
Console
Import the NumPy package 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.

  • HTML
Executing Python code 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.

  • 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.

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 extensive documentationhttps://pyodide.org/en/stable/index.html# that we can look into for a better understanding and further use.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved