python in your browser... in javascript!
I’ve recently been looking for ways to run Python in a browser. There are lots of reasons why I think this is a cool idea. For example, creating some simple tutorials, Making some online quizzes and tests, getting Python to run on my iPad…
It looks like there are two projects that are actively working on solving this problem. The first is called skulpt (see the demo on skulpt.org.) This project actually reimplements the core of Python in Javascript by hand. They are working on some modules, but right now it is basically the core Python language.
The other project uses Emscripten to compile the CPython C source code to javascript! Yep you read that right. You can see here that the core of Python 2.7 is running. You can import sys, but thats about it. Nevertheless both of these are really useful for beginning Python exercises.
The problem with both of these is that right now there is no user level documentation. Skulpt is particularly difficult as you can’t even look at the demo page to see how its done. You need to go digging through some additional source files from the distribution to figure out how to make it work for yourself. The source code of the syntensity page is pretty easy to follow. So here’s a hello world program using skulpt.
<script src=“skulpt.js” type=“text/javascript”>
</script>
<script type=“text/javascript”>
function outf(text) {
var mypre = document.getElementById(“output”);
mypre.innerHTML = mypre.innerHTML + text;
}
function runit() {
var prog = document.getElementById(“yourcode”).value;
var mypre = document.getElementById(“output”);
mypre.innerHTML = “;
Sk.configure({output:outf});
try {
eval(Sk.importMainWithBody(”<stdin>”,false,prog));
} catch (e) {
alert(e);
}
}
</script>
<h3>Try This</h3>
<form>
<textarea edit_id=“eta_5” id=“yourcode”>
print “Hello World”
</textarea>
<button onclick=“runit()” type=“button”>Run</button>
</form>
<pre id=“output”></pre>
Its a bit on the verbose side, and it could certainly be improved so that less code would have to be replicated if you wanted to put multiple input/output areas on a single page, but as a learning example I think it works OK. The try/catch block around the Sk.importMainWithBody function call will capture Python runtime errors and throw them. This is a nice way to inform your users of syntax errors in any code they are trying out.
I’m certainly no expert in either implementation, I just offer this post as an example and a time saver for anyone else trying to get going with either implementation.