xiaoqianbook

参考官方文档安装

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方式保存

 

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2021-09-02
  • 2022-12-23
  • 2022-01-01
  • 2021-09-20
  • 2021-07-13
  • 2022-01-09
  • 2021-08-25
猜你喜欢
  • 2022-03-08
  • 2021-12-11
  • 2022-12-23
  • 2022-02-23
  • 2021-12-15
  • 2021-11-23
  • 2021-07-28
相关资源
相似解决方案