coldbrew

Coldbrew: Run Python in JavaScript

Coldbrew is installed on this page through https://cdn.jsdelivr.net/gh/plasticityai/coldbrew@0.0.74/dist/coldbrew.js.

Open the browser console and try running some of these examples in the console.

Start by loading Coldbrew with:

Coldbrew.load().then(function() { console.log("Finished loading Coldbrew!") });


Once loaded, you can interact with Python. For example, to print the version of Python run the following in the browser console:

Coldbrew.run("import sys");
Coldbrew.run("print('The current Python version is:', sys.version)");


You can also issue multiple commands in the same function call, to see this, run the following in the browser console:

Coldbrew.run(["x = [i for i in range(10)]","print(x)"].join("\n"));


You can run a Python file like add.py with arguments and environment variables specified, to see this, run the following in the browser console:

Coldbrew.runFile('add.py', {cwd:'/coldbrew/examples', env:{}, args:['5', '15', '-v']});


You can access HTTP connections in Python and the requests will be handled by JavaScript's XHR / AJAX requests:

Coldbrew.runAsync('import urllib.request; print(urllib.request.urlopen("http://coldbrew.plasticity.ai/remote/example.txt").read())');


You can export Python variables (objects, classes, functions, modules, primitives, etc.) and use them like a native JavaScript variable using Coldbrew's bridge variables, like, for example, the Counter class:

Coldbrew.run("from collections import Counter");
var Counter = Coldbrew.getVariable("Counter");
var c = new Counter(['red', 'blue', 'red', 'green', 'blue', 'blue']);
console.log(c.mostCommon(2));


You can run Python code asynchronously, which won't lock up the browser for long-running code.

See the difference between running this:

for(var i=0; i<5; i++) { setTimeout(function() { console.log("Every 1 second for 5 seconds from JavaScript.") }, (i+1)*1000); }
Coldbrew.runAsync('from time import sleep\nfor i in range(5):\n\tsleep(1)\n\tprint("Every 1 second for 5 seconds from Python.")');

And this:

for(var i=0; i<5; i++) { setTimeout(function() { console.log("Every 1 second for 5 seconds from JavaScript.") }, (i+1)*1000); }
Coldbrew.run('from time import sleep\nfor i in range(5):\n\tsleep(1)\n\tprint("Every 1 second for 5 seconds from Python.")');


See more documentation on GitHub
for more information on interacting with the virtual filesystem, installing modules, interacting with the environment, running Python asynchronously, communicating bi-directionally between the two languages, building a custom Coldbrew Python environment, and more.