python 调用 js

安装 pyexecjs

pip install PyExecJS2

使用

import os
import execjs
import execjs.runtime_names

current_dir = os.path.dirname(__file__)
js_abs_path = os.path.join(current_dir, "js\\index.js")

'''js内容
function add(a, b){
  return a + b;
}
'''

def readFile(path):
    with open(path, 'r') as f:
        js = f.read()
        return js

# 获取 js 文本
indexJs = readFile(js_abs_path)

# 使用 node 环境
node = execjs.get(execjs.runtime_names.Node)
ctx = node.compile(indexJs)

# 调用 add 方法
v = ctx.call('add', 2, 3)
print(v)
# 5
posted @ 2024-03-27 20:38  灵火  阅读(3)  评论(0编辑  收藏  举报