目录
-
-
-
-
- 零、样例demo.js
- 一、execjs
- 二、MiniRacer
- 三、NodeVM
- 四、nodejs服务调用
零、样例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))
- 调用方式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服务调用