74

Is it possible to integrate Python and JavaScript? For example, imagine you wanted to be able to define classes in JavaScript and use them from Python (or vice versa). If so, what's the best way? I'm interested not only if this is possible but if anyone has done it within a "serious" project or product.

I'm guessing it would be possible using Jython and Rhino, for one example, but I'm curious whether or not anyone's ever actually done this, and if there are solutions for other platforms (especially CPython).

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Jacob Gabrielson
  • 34,800
  • 15
  • 46
  • 64
  • 1
    Perhaps you could compile CPython to JavaScript using Emscripten, and then run CPython in the browser. It might be possible to call Python functions from JavaScript, and vice versa. http://syntensity.com/static/python.html – Anderson Green Feb 09 '13 at 05:05
  • 1
    @AndersonGreen this was already done: pypyjs - https://github.com/rfk/pypyjs – denfromufa Feb 27 '15 at 16:48
  • For what it's worth, [this SO answer](https://stackoverflow.com/a/28652754/1519199) presents a unified approach to sharing objects between JS and Python, and is implemented in [this repo](https://github.com/jdthorpe/ajvpy) which simply wraps a NodeJS module bundled via webpack and exposes it as a Python Module. – Jthorpe Jun 30 '17 at 17:52
  • 1
    **For those finding this on Google**, checkout my modern answer with JSPyBridge below. – Extreme Jul 23 '21 at 10:16

13 Answers13

28

How about pyjs?

From the above website:

pyjs is a Rich Internet Application (RIA) Development Platform for both Web and Desktop. With pyjs you can write your JavaScript-powered web applications entirely in Python.

Elazar
  • 20,415
  • 4
  • 46
  • 67
Stephen Simmons
  • 7,941
  • 2
  • 21
  • 13
21

Here's something, a Python wrapper around the SeaMonkey Javascript interpreter... http://pypi.python.org/pypi/python-spidermonkey

David Z
  • 128,184
  • 27
  • 255
  • 279
17

This question is not exactly young, but there have come up some alternatives:

  • "Skulpt is an entirely in-browser implementation of Python."
  • Brython - "A Python 3 implementation for client-side web programming"
  • RapydScript - "Python-like JavaScript without the extra overhead or quirks"
  • Transcrypt - "Lean and mean Python 3.6 to JavaScript compiler with multiple inheritance, sourcemaps, static type checking and selective operator overloading." (also on Github)
Jacques de Hooge
  • 6,750
  • 2
  • 28
  • 45
Tobias Kienzler
  • 25,759
  • 22
  • 127
  • 221
  • 6
    Just to add my two cents, both Skulpt and Brython are toys rather than full-blown compilers/languages. RapydScript and Transcrypt will run circles around them performance-wise. In fact, the absence of performant Python interpreter in JS was the reason RapydScript was invented to begin with. RapydScript now has an added benefit of type safety, just like TypeScript. disclaimer: I'm the RapydScript maintainer. – Alexander Tsepkov Sep 25 '16 at 21:17
  • @AlexanderTsepkov I didn't have time to test those, so thanks for you additions :) – Tobias Kienzler Sep 26 '16 at 11:19
  • 1
    Transcrypt can be pip-installed, nice if you don't wish to immerse yourself in the js ecosystem. RapydScript however seems to be the quickest transpiled option as far as I gathered so far. A nice array of options is described [here](https://github.com/zoofIO/flexx/wiki/PyScript-vs-X). There is also [Jiphy](https://github.com/timothycrosley/jiphy) which seems unmaintained. – Jay Jul 23 '17 at 11:49
10

there are two projects that allow an "obvious" transition between python objects and javascript objects, with "obvious" translations from int or float to Number and str or unicode to String: PyV8 and, as one writer has already mentioned: python-spidermonkey.

there are actually two implementations of pyv8 - the original experiment was by sebastien louisel, and the second one (in active development) is by flier liu.

my interest in these projects has been to link them to pyjamas, a python-to-javascript compiler, to create a JIT python accelerator.

so there is plenty out there - it just depends what you want to do.

7

If your just interested in sharing complex data types between javascript and python, check out jsonpickle. It wraps the standard Python JSON libraries, but has some smarts in serializing and deserializing Python classes and other data types.

Quite a few Google App Engine projects have used this library. Joose and FirePython both incorporate jsonpickle.

John Paulett
  • 15,596
  • 4
  • 45
  • 38
  • Note that jsonpickle uses a non-standard "py/ref" reference type that makes it harder to use for non-python clients. There's currently no way to turn it off. http://code.google.com/p/jsonpickle/issues/detail?id=9 – pimlottc Oct 19 '09 at 16:22
4

PyExecJS is able to use each of PyV8, Node, JavaScriptCore, SpiderMonkey, JScript.

>>> import execjs
>>> execjs.eval("'red yellow blue'.split(' ')")
['red', 'yellow', 'blue']
>>> execjs.get().name
'Node.js (V8)'
iman
  • 21,202
  • 8
  • 32
  • 31
4

Many of the examples are years out of date and involve complex setup. You can give JSPyBridge a try (full disclosure: I'm the author).

It's a bi-directional bridge that lets you use JavaScript code from Python, and vice-versa. That means that Python code can call JS callbacks, and JS code can call Python callbacks.

Access Python from JS, numpy + matplotlib example, with the ES6 import system:

import { py, python } from 'pythonia'
const np = await python('numpy')
const plot = await python('matplotlib.pyplot')

// Fixing random state for reproducibility
await np.random.seed(19680801)
const [mu, sigma] = [100, 15]
// Inline expression evaluation for operator overloading
const x = await py`${mu} + ${sigma} * ${np.random.randn(10000)}`

// the histogram of the data
const [n, bins, patches] = await plot.hist$(x, 50, { density: true, facecolor: 'g', alpha: 0.75 })
console.log('Distribution', await n) // Always await for all Python access
await plot.show()
python.exit()

Through CommonJS (without top level await):

const { py, python } = require('pythonia')
async function main() {
  const np = await python('numpy')
  const plot = await python('matplotlib.pyplot')
  ...
  // the rest of the code
}
main().then(() => python.exit()) // If you don't call this, the process won't quit by itself.

Access JS from python:

from javascript import require, globalThis

chalk, fs = require("chalk"), require("fs")

print("Hello", chalk.red("world!"), "it's", globalThis.Date().toLocaleString())
fs.writeFileSync("HelloWorld.txt", "hi!")
Extreme
  • 315
  • 4
  • 7
3

Use Js2Py to translate JavaScript to Python, this is the only tool available :)

Piotr Dabkowski
  • 5,661
  • 5
  • 38
  • 47
2

There's a bridge based on JavaScriptCore (from WebKit), but it's pretty incomplete: http://code.google.com/p/pyjscore/

Miles
  • 31,360
  • 7
  • 64
  • 74
2

You might also want to check out the PyPy project - they have a Python to (anything) compiler, including Python to Javascript, C, and llvm. This allows you to write your code in Python and then compile it into Javascript as you desire.

http://codespeak.net/pypy

Also, check out the informative blog:

http://morepypy.blogspot.com/

Unfortunately though, you can't convert Javascript to Python this way. It seems to work really well overall, they used to have a Javascript (made from compiled Python) version of the Bub'n'Bros game online (though the server has been down for a while).

http://bub-n-bros.sourceforge.net

1

You could also use XPCOM, say in XUL based apps like Firefox, Thunderbird or Komodo.

Malekai
  • 4,765
  • 5
  • 25
  • 60
liucougar
  • 11
  • 1
1

Many of these projects mentioned above are dead or dying, lacking activity and interest from author side. Interesting to follow how this area develops.

For the record, in era of plugin based implementations, KDE camp had an attempt to solve this with plugin and non-language specific way and created the Kross https://en.wikipedia.org/wiki/Kross_(software) - in my understanding it never took off even inside the community itself.

During this chicken and egg -problem time, javascript-based implementions are definately way to go. Maybe in the future we seee pure and clean, full Python support natively in browsers.

Stephen Docy
  • 4,738
  • 7
  • 18
  • 31
Juha Tuomala
  • 111
  • 11
1

I was playing with Pyjon some time ago and seems manage to write Javascript's eval directly in Python and ran simple programs... Although it is not complete implementation of JS and rather an experiment. Get it here:

http://code.google.com/p/pyjon/

buzzilo
  • 91
  • 1
  • 2