參考官方文檔安裝
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方式保存