Python in the browser: Brython

Introduction
  • Convert Python code to JavaScript, allowing us to write and run Python code in the browser.
  • It is possible to realize that python and js codes can call each other.
  • Based on Python 3 implementation, supports HTML5 environment (providing DOM objects and event interfaces).
  • Supports turtle drawing library, which can draw images. Brython will convert drawing programs into animations in svg format.
  • Brython only supports native Python modules, not C built-in Python modules, unless they have been reimplemented in JavaScript.
  • Because Brython runs in the context of a web browser, there are some limitations. For example, browsers do not allow direct access to the file system, so os.open() cannot open the file. Web browser-independent features may not be available.

Brython project mirror directory: brython download | SourceForge.net

Using Brython
  • 1. Load the brython.js library into the section of the HTML page
$ npm install brython
<script src="node_modules/brython/brython.js"></script>

// Or load the brython library from CDN. There are several CDNs to choose from:
<!-- 1 : jsDelivr CDN -->
<script src="//i2.wp.com/cdn.jsdelivr.net/npm/[email protected]/brython.min.js"></script>
<script src="//i2.wp.com/cdn.jsdelivr.net/npm/[email protected]/brython_stdlib.js"></script>

<!-- 2: CloudFlare CDN -->
<script src="//i2.wp.com/cdnjs.cloudflare.com/ajax/libs/brython/3.9.1/brython.min.js"></script>
<script src="//i2.wp.com/cdnjs.cloudflare.com/ajax/libs/brython/3.9.1/brython_stdlib.min.js"></script>

<!-- 3: GitHub as the CDN -->
<!--If you want to use the latest development version, you can select this option -->
<script src="//i2.wp.com/raw.githack.com/brython-dev/brython/master/www/src/brython.js"></script>
<script src="//i2.wp.com/raw.githack.com/brython-dev/brython/master/www/src/brython_stdlib.js"></script>

Of course, you can also download it locally and then load it, so the loading speed will be much faster.

  • 2. Translation in Brython occurs while loading the HTML page, so we need to call the function brython() in the body tag of the HTML document.
<body onload="brython()">

  • 3. The brython() function will search for all script tags with the type =”text/python” attribute in the HTML document, thereby translating the Python code in the tag. Therefore, Python code must be surrounded by