Python调用js的方式

零、样例demo.js
// demo.js
function get_m(a, b){
    
    
    m = a+b
    return m
}

module.exports = {
    
    
    get_m
}
一、execjs
  • 依赖:execjs会自动使用当前电脑上的运行时环境(建议用nodejs)
  • 安装:pip install PyExecJS
  • 导包:import execjs
  • 调用方式1: execjs.compile(js代码).call(函数名参数1参数2) ,此种方式建议js代码存到文件中
    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
    
  • 调用方式2:execjs.eval(js代码)
    import execjs
    
    print(execjs.eval("cookie='Hm_lvt_444ece9ccd5b847838a56c93a0975a8b=1636208098'"))
    
二、MiniRacer
  • 安装:pip install py_mini_racer
  • 导包:from py_mini_racer import MiniRacer
  • 调用方式如下
    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))
    
三、NodeVM
  • 安装:pip install node_vm2
  • 导包:from node_vm2 import NodeVM
  • 调用方式1如下:调用js文件
    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))
    
  • 调用方式2如下:使用eval
    from node_vm2 import eval
    
    print(eval("cookie='Hm_lvt_444ece9ccd5b847838a56c93a0975a8b=1636208098'"))
    
  • 换了个电脑环境突然报错:TypeError: write() argument must be str, not bytes ,首先第一步488行去掉.encode("utf-8")
    在这里插入图片描述
    在这里插入图片描述
  • 然后运行接着又报错'str' object has no attribute 'decode',然后去掉395行如下的.decode("utf-8"),然后就正常了
    在这里插入图片描述
    在这里插入图片描述
四、nodejs服务调用

猜你喜欢

转载自blog.csdn.net/weixin_43411585/article/details/121595477