The way Python calls js

Zero, sample demo.js
// demo.js
function get_m(a, b){
    
    
    m = a+b
    return m
}

module.exports = {
    
    
    get_m
}
1. execjs
  • Dependency: execjs will automatically use the runtime environment on the current computer (nodejs is recommended)
  • Install:pip install PyExecJS
  • Guide package:import execjs
  • Calling method 1: execjs.compile( js代码).call( 函数名, 参数1, 参数2) , this method is recommended to save the js code in the file
    import execjs
    
    with open(r"./demo.js", encoding="utf-8") as f:
        ctx = execjs.compile(f.read())
        print(ctx.call('get_m', 5, 6))  # 11
    
  • Calling method 2: execjs.eval( js代码)
    import execjs
    
    print(execjs.eval("cookie='Hm_lvt_444ece9ccd5b847838a56c93a0975a8b=1636208098'"))
    
Two, MiniRacer
  • Install:pip install py_mini_racer
  • Guide package:from py_mini_racer import MiniRacer
  • The calling method is as follows
    from py_mini_racer import MiniRacer
    
    with open(r"./demo.js", encoding="utf-8") as f:
        ctx = MiniRacer()
        ctx.eval(f.read())
        print(ctx.call('get_m', 5, 6))
    
3. NodeVM
  • Install:pip install node_vm2
  • Guide package:from node_vm2 import NodeVM
  • Call method 1 is as follows: call js file
    from node_vm2 import NodeVM
    
    with open(r"./demo.js", encoding="utf-8") as f:
        ctx = NodeVM.code(f.read())
        print(ctx.call_member("get_m", 5, 6))
    
  • The calling method 2 is as follows: use eval
    from node_vm2 import eval
    
    print(eval("cookie='Hm_lvt_444ece9ccd5b847838a56c93a0975a8b=1636208098'"))
    
  • Changed the computer environment and suddenly reported an error: TypeError: write() argument must be str, not bytes, the first step is to remove line 488.encode("utf-8")
    insert image description here
    insert image description here
  • Then run and then report an error 'str' object has no attribute 'decode', then remove the line 395 as follows .decode("utf-8"), and then it will be normal
    insert image description here
    insert image description here
Four, nodejs service call

Guess you like

Origin blog.csdn.net/weixin_43411585/article/details/121595477