1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| # Adding Python built-in sum to the JS context: >>> context = js2py.EvalJs({'python_sum': sum}) >>> js_code = ''' var a = 10 function f(x) {return x*x} ''' >>> context.execute(js_code) # Get value of variable a: >>> context.a 10 # context.f behaves just like js function so you can supply more than 1 argument. '9'*'9' in javascript is 81. >>> context.f('9', 0) 81 # context.f has all attributes of normal JavaScript object >>> context.f.toString() u'function f(x) { [python code] }' >>> context.f.bind function bind(thisArg) { [python code] } # You can also add variables to the context: >>> context.foo = [1,2,3] # context.foo is now Js Array object and behaves just like javascript array! >>> context.foo.push(4) 4 >>> context.foo.to_list() # convert to python list [1, 2, 3, 4] # You can use Python objects that you put inside the context! >>> context.eval('python_sum(new Array(1, 2, 3))')
|