参考官方文档安装
pip3 install PyExecJS
代码编写
import execjs ctx = execjs.compile(""" function add(x, y) { return x + y; } """) # 获取代码编译完成后的对象 print(ctx.call("add", 1, 2)) # 3 # print(ctx.eval("add({0},{1})").format(1,2)) # 报错 print(ctx.eval(\'add("{0}", "{1}")\').format("1","2")) # 12
文件读取代码编写
创建jsCode.js的文件
function add(x, y) { return x + y; }
执行代码
import execjs file = \'jsCode.js\' ctx = execjs.compile(open(file).read()) js = \'add("{0}", "{1}")\'.format("1","2") params = ctx.eval(js) print(params) # 12 params = ctx.call(\'add\',1,2) print(params) # 3
出现错误提示
UnicodeEncodeError: \'gbk\' codec can\'t encode character xxx
解决方案一
添加encoding="utf-8"
ctx = execjs.compile(open(file,encoding="utf-8").read())
解决方案二
js文件以GBk方式保存