Sunday, 22 March 2015

Brython: Python in Browser

Brython is python in browser.

Yes, You can just run it in the browser.

What you need is to get brython.js from their github.

https://raw.githubusercontent.com/brython-dev/brython/master/www/src/brython.js

And put it into some folder of your choice.

Now create a html file and call that js.


<html>
<head>
<script src="brython.js"></script>
</head>
<body onload="brython()">
<script type="text/python">
from browser import document, alert, console

def echo(ev):
    alert(document["zone"].value)

console.log('Hi, this is from python')
document['mybutton'].bind('click',echo)
</script>
<input id="zone"><button id="mybutton">click !</button>
</body>
</html>

Here is piece of code i copied from their website (Infact, modified a little bit).

What is important?
1. including

 <script src="brython.js"></script>

Yes this line, calling/including browser.js file.

3.Body onload function 

<html>

<head>
<script src="brython.js"></script>
</head>

<body onload="brython()">
<script type="text/python" src="test.py"></script>
<input id="zone"><button id="mybutton">click!</button>
</body>

</html>

And here is python code (test.py) i used


from browser import document, alert, console

def echo(ev):
    alert(document["zone"].value)

console.log('Hi, this is from python')
document['mybutton'].bind('click',echo)


Here you can try it online

http://brython.info/tests/console.html

OR Here

http://brython.info/tests/editor.html