最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Call Javascript from python - Stack Overflow

programmeradmin0浏览0评论

I am looking for a way to call a js function from a python function. I am coming to you because I also need my js function to use DOM, so pyv8 for example is not a solution.. Do you guys have any idea? Is it even possible?

Thanks in advance.

I am looking for a way to call a js function from a python function. I am coming to you because I also need my js function to use DOM, so pyv8 for example is not a solution.. Do you guys have any idea? Is it even possible?

Thanks in advance.

Share Improve this question asked Aug 23, 2016 at 9:06 soukisouki 1,3854 gold badges25 silver badges42 bronze badges 3
  • "I also need my js function to use DOM". The javascript DOM exists in the browser (unless you're emulating it). Python runs on the server. Are you asking how you can trigger execution of browser-side javascript from python code? – Levi Commented Aug 23, 2016 at 9:15
  • Yes that's it. Kode.Error404's solution seems fine. – souki Commented Aug 23, 2016 at 9:17
  • Possible duplicate of Call Javascript function from Python – Stevoisiak Commented Oct 17, 2017 at 15:10
Add a comment  | 

3 Answers 3

Reset to default 6

According to https://stackoverflow.com/a/30537286/6353933,

import js2py

js = """
function escramble_758(){
var a,b,c
a='+1 '
b='84-'
a+='425-'
b+='7450'
c='9'
document.write(a+c+b)
}
escramble_758()
""".replace("document.write", "return ")

result = js2py.eval_js(js)  # executing JavaScript and converting the result to python string 

Advantages of Js2Py include portability and extremely easy integration with python (since basically JavaScript is being translated to python).

To install:

pip install js2py

PyExecJS seems to be a good option.

>>> import execjs
>>> execjs.eval("'red yellow blue'.split(' ')")
['red', 'yellow', 'blue']
>>> ctx = execjs.compile("""
...     function add(x, y) {
...         return x + y;
...     }
... """)
>>> ctx.call("add", 1, 2)
3

to install:

$ pip install PyExecJS

PythonMonkey can be used to execute JavaScript and WebAssembly in Python.

import pythonmonkey as pm

pm.eval("""
function add(x, y) {
    return x + y;
}
""")

js_adder = pm.eval('add')

print(js_adder(1,2)) # outputs 3.0

pm.eval('console.log("Hello from JavaScript");') # outputs: Hello from JavaScript

Installation:

$ pip install pythonmonkey
发布评论

评论列表(0)

  1. 暂无评论