Conversion from JavaScript to Python code?

user282583 picture user282583 · Feb 27, 2010 · Viewed 74.3k times · Source

Is there a relatively quick program out there to accomplish at least the basics of this? Just a few regexes? I'm willing to do some manual conversion, but this is a pretty big set of scripts.

Answer

Piotr Dabkowski picture Piotr Dabkowski · Dec 10, 2014

You can translate JavaScript to Python using Js2Py. It supports whole JavaScript and you can use it to translate large JavaScript modules like esprima.js (a JavaScript 6 parser).


Short demo:

>>> import js2py
>>> f = js2py.eval_js( "function $(a) {return a + arguments[1]}" )
>>> f
function $(a) { [python code] }
>>> f(1, 2, 3)
3

This is how the translated function looks like internally (it's rather ugly):

>>> print js2py.translate_js( "function $(a) {return a + arguments[1]}" )
from js2py.pyjs import *
var = Scope( JS_BUILTINS )
set_global_object(var)
# Code follows:
var.registers([u'$'])
@Js
def PyJsHoistedNonPyName(a, this, arguments, var=var):
    var = Scope({u'a':a, u'this':this, u'arguments':arguments}, var)
    var.registers([u'a'])
    return (var.get(u'a')+var.get(u'arguments').get(u'1'))
PyJsHoistedNonPyName.func_name = u'$'
var.put(u'$', PyJsHoistedNonPyName)