Build Python code editor using CodeMirror and pyodide
In this article, we will learn to develop an application which can run the Python code inside your web browser.
To achieve this, we will use pyodide.org, which consists of the CPython interpreter compiled to WebAssembly which allows Python to run in the browser. We are going to use codemirror.net in Python-mode as a code-editor component. You can find the API reference and source code links at the end of this article.
Let us take a quick look at our project structure:
Let us begin with the user interface component, index.html file:
We define our output element, which represents the textarea element with id “output” using document.getElementById. To initialize the editor, we make use of the method fromTextArea provided by CodeMirror, which replaces the textarea with a CodeMirror instance. The text in the textarea will provide the content for the editor which we later access using editor.getValue(). To setup the pyodide, we define an async function main(), which calls the loadPyodide method, with the indexURL as the latest version of pyodide, provided by CDN service. It sets up the Python environment and returns the Pyodide top level namespace as a promise. Now, pyodide is ready to use.
That is all, we have built a simple code editor which can execute python code inside the browser! As a fun little activity, you can try to build another component, Debug Output, which would display the result of all print statements inside code, as default the result is displayed in the console.
To run this application, just open the index.html inside your browser: