Preface
In traditional web development, Python is usually more used as a server-side language (such as Django, Flask, etc.), while on the browser side (front-end), JavaScript is usually used to operate DOM, perform event processing, etc. However, with the development of WebAssembly technology and the emergence of some Python-to-JavaScript translation solutions, we can already run (or compile) Python code directly on the front-end.
The following will introduce the various main ways to run Python programs on the front end, their advantages and limitations, and will come with some examples or basic usage ideas.
1. Run Python directly in the browser: Pyodide based on WebAssembly
1. What is Pyodide
PyodideIt is based onWebAssemblyA complete Python interpreter project that compiles CPython (Python's official interpreter) into a version that can be executed in a browser environment (or other WebAssembly running environment). In other words, you don't need to install any plug-ins, as long as the browser supports WebAssembly, you can run almost complete Python in the front-end environment.
2. The main features of Pyodide
- Good compatibility: Almost completely ported CPython, including support from standard libraries and some third-party libraries (such as NumPy, Pandas, etc.).
-
Easy integration: Officially provided a
(or
), the front-end can be used as long as it is introduced.
- WebAssembly Performance: Compared with pure JavaScript explanation of Python solutions, Pyodide performs better.
3. How to use Pyodide
-
IntroducedFrom official CDN or local hosting, introduce Pyodide scripts:
<script src="/pyodide/v0.23.4/full/"></script>
Tip: The version number may be updated continuously, you can goPyodide ReleasesCheck out the latest version.
-
Initialize the Pyodide environment
<script> async function initPyodide() { // Load Pyodide let pyodide = await loadPyodide(); // You can use Python code to execute let result = (\` import sys \`); ("Python version:", result); } initPyodide(); </script>
-
Execute Python code
-
(code)
You can directly execute a Python code string and return the value of the last line of expression (if any). -
You can get variables with global scope in the current Python interpreter.
- In addition to executing simple scripts, third-party libraries can also be loaded (some pure Python libraries have been precompiled into Pyodide).
Example:
<script> async function initPyodide() { let pyodide = await loadPyodide(); // Install / Load some packages await ("micropip"); // micropip can install more Python packages, but it needs to be compatible with WASM, such as the package mentioned in // Run simple Python code let code = \` import math def compute_circle_area(r): return * (r ** 2) area = compute_circle_area(5) \`; (code); let area = ("area"); ("Circle area:", area); } initPyodide(); </script>
-
4. Pros and cons
-
advantage:
- It supports the Python ecosystem almost completely and can directly use many Python packages, especially scientific computing related.
- Relying on WebAssembly, it highly restores CPython functions, and its operational efficiency is higher than that of other pure JS interpreters.
-
shortcoming:
- It is large in size and requires loading compiled Python interpreter and related packages. The initial loading may be time-consuming.
- Not all Python packages can be used in Pyodide, and some libraries that rely on local C/C++ extensions need to be ported specifically.
2. Brython: Use Python as the browser scripting language
1. What is Brython
BrythonIt is a Python interpreter implemented in JavaScript. Its goal is to allow Python to replace JavaScript in front-end development. It provides a runtime environment that uses pure JavaScript to interpret Python syntax, and encapsulates a series of DOM operations, browser interfaces, etc., so that you can operate browser objects like you write JavaScript.
2. Use of Brython
-
Introducing Brython
<script src="/npm/[email protected]/"></script> <script src="/npm/[email protected]/brython_stdlib.js"></script>
-
HTML tagging and startupexist
<body>
Add to the tagonload="brython()"
Or use JavaScript to initialize Brython after loading the DOM:<body onload="brython()"> ... </body>
- exist
<script type="text/python">
Writing PythonBrython allows us to use it directly in HTML files<script type="text/python">
Tags to write front-end Python code, such as:here<script type="text/python"> from browser import document, alert def greet(ev): alert("Hello from Brython!") document["mybutton"].bind("click", greet) </script>
document["mybutton"]
With the JavaScript("mybutton")
Similar.
3. Pros and cons
-
advantage:
- Very simple to use, direct
<script type="text/python">
You can write code. - The DOM operation is encapsulated to allow Python code to operate the browser API.
- The code size is smaller than Pyodide (after all, there is no complete porting of CPython).
- Very simple to use, direct
-
shortcoming:
- Brython does not include a complete Python standard library implementation, and its functions are limited in some scenarios.
- Since it is a pure JavaScript explanation, performance impact needs to be considered, and complex computing performance may be much lower than that of WebAssembly solutions.
- Some Python third-party libraries may not be directly used or require dependency on specific Polyfills.
3. Transcrypt: Python translation into JavaScript
1. What is Transcrypt
TranscryptIt is a tool that compiles Python code into high-quality, highly readable JavaScript code. You can write logic in Python during the development stage, and then compile it into JavaScript through Transcrypt, and finally JavaScript is still running on the browser side.
2. Workflow
- Install Transcrypt:
pip install transcrypt
- Compile Python files using Transcrypt:
transcrypt -b -m
-
-b
Indicates compilation in browser mode (browser). -
-m
Indicates the generation of a mapping file (source map).
-
- After compilation is completed, a
__javascript__
Folder, insideand dependency files.
- Introduce compiled JS files in HTML:
<script src="__javascript__/"></script>
- This way, the converted JS logic can be used on the browser side.
3. Pros and cons
-
advantage:
- Maintains the development experience of Python syntax.
- The resulting JavaScript is relatively small and has no additional runtime dependencies.
- The compiled speed is similar to JavaScript itself (the final product is JS after all).
-
shortcoming:
- It is not to directly execute Python in the browser, but to translate Python into JS. To some extent, there are certain restrictions on the Python syntax.
- Some dynamic features and some library support for Python are imperfect.
4. Skulpt, RapydScript and other solutions
In addition to the above solutions, there are also some projects that can help run (or approximately) Python on the front-end:
-
Skulpt
- A pure JavaScript-implemented Python interpreter.
- Supports a subset of Python syntax for teaching or simple scripting scenarios.
- The complete standard library is not supported.
-
RapydScript
- A Python-like syntax compiled into efficient JavaScript.
- It is closer to an independent language, with the characteristics of Python and JavaScript.
-
Online platforms such as Trinket and Replit
- Run Python code directly on the web page through a remote server or WebAssembly embedded method.
- Suitable for teaching, demonstration or small project trials.
5. Choice suggestions suitable for different scenarios
-
If you want to run Python completely on the browser side and use scientific computing libraries (such as NumPy, Pandas, etc.)
- PyodideIt is the preferred solution, but pay attention to loading speed, compatibility and memory usage.
-
If you want to use Python syntax to manipulate DOM on the front end, replace some JavaScript functions
- BrythonYou can try it, but pay attention to the support and performance of third-party libraries.
-
If your core requirement is still to convert Python logic into the final JavaScript
- TranscryptIt can help you obtain optimized pure JS code while maintaining the Python development experience.
-
If you are teaching or simple Python script interaction
- Skulpt、TrinketThis type of project or online platform can be quickly started, but its functions are relatively limited.
6. Summary
Running Python in a browser is no longer a distant idea. With the popularity of WebAssembly and the emergence of multiple Python-to-JavaScript solutions, the integration between the front-end and the Python ecosystem will become increasingly close. When choosing a specific plan, you need to consider comprehensively:
- Do I need to use a lot of Python third-party libraries?
- What are the requirements for performance and package volume?
- Do I need to call the browser's DOM or Web API?
- Is it just teaching and experiment, or should it be applied to the production environment?
Whether it is Pyodide directly based on WebAssembly, Brython implemented by JavaScript, or Transcrypt compiled/translated to JavaScript, they are all optional ideas in different scenarios. In the future, with the further development of Web technology, the combination of front-end and Python will be easier and more efficient. Hope the above introduction can help you better understand and choose the best way to run Python on the front end.
This is the article about how to run Python programs on the front-end of the browser. For more related contents of running Python programs on the front-end of the browser, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!