2022年 11月 5日

Python调用js的方式

目录

          • 零、样例demo.js
          • 一、execjs
          • 二、MiniRacer
          • 三、NodeVM
          • 四、nodejs服务调用
零、样例demo.js
// demo.js
function get_m(a, b){
    m = a+b
    return m
}

module.exports = {
    get_m
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
一、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
    
    • 1
    • 2
    • 3
    • 4
    • 5
  • 调用方式2:execjs.eval(js代码)
    import execjs
    
    print(execjs.eval("cookie='Hm_lvt_444ece9ccd5b847838a56c93a0975a8b=1636208098'"))
    
    • 1
    • 2
    • 3
二、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))
    
    • 1
    • 2
    • 3
    • 4
    • 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))
    
    • 1
    • 2
    • 3
    • 4
    • 5
  • 调用方式2如下:使用eval
    from node_vm2 import eval
    
    print(eval("cookie='Hm_lvt_444ece9ccd5b847838a56c93a0975a8b=1636208098'"))
    
    • 1
    • 2
    • 3
  • 换了个电脑环境突然报错:TypeError: write() argument must be str, not bytes ,首先第一步488行去掉.encode("utf-8")
    在这里插入图片描述
    在这里插入图片描述
  • 然后运行接着又报错'str' object has no attribute 'decode',然后去掉395行如下的.decode("utf-8"),然后就正常了
    在这里插入图片描述
    在这里插入图片描述
四、nodejs服务调用
  • 该文章末尾