js2py基本使用

发布时间 2023-03-23 03:15:16作者: 与鹿逐秋

一、安装

pip install js2py

二、执行js单语句

import js2py

js2py.eval_js('console.log("hello world!")')
# 'hello world!'

三、执行js代码块

import js2py

js_code = '''
        function add(x, y){
            return x + y;
        }
    '''
add_func = js2py.eval_js(js_code)
print(add_func(3, 6))
# 9

四、引入js文件

  • js文件
function add(x, y) {
    return x + y;
}

function sub(x, y) {
    return x - y;
}
  • python
import js2py

ctx = js2py.EvalJs()
ctx.execute(open('./test.js', 'r', encoding='utf-8').read())
print(ctx.add(5, 6))
print(ctx.sub(10, 5))
# 11 5