python:python执行js

一,安装node

安装Node.js(推荐)

$ node -v
v22.20.0

二,安装python库

$ pip install PyExecJS
Collecting PyExecJS
  Downloading PyExecJS-1.5.1.tar.gz (13 kB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Preparing metadata (pyproject.toml) ... done
Collecting six>=1.10.0 (from PyExecJS)
  Downloading six-1.17.0-py2.py3-none-any.whl.metadata (1.7 kB)
Downloading six-1.17.0-py2.py3-none-any.whl (11 kB)
Building wheels for collected packages: PyExecJS
  Building wheel for PyExecJS (pyproject.toml) ... done
  Created wheel for PyExecJS: filename=pyexecjs-1.5.1-py3-none-any.whl size=14649 sha256=19677164f4303803756805f1a29a6bcd66ff7fa5f4d21b66ea740d25a1d836fb
  Stored in directory: /home/liuhongdi/.cache/pip/wheels/95/1c/16/774a935204aacf741cea3deae76c535050d19727c72613d80f
Successfully built PyExecJS
Installing collected packages: six, PyExecJS
Successfully installed PyExecJS-1.5.1 six-1.17.0

三,执行js代码

代码:

import execjs

# 直接执行
print(execjs.eval('"abc aaa bbb".split(" ")'))

# 编译后调用
js_code = """
var t1="aaaa"
function add1(x, y) {
    return x + y;
}
"""
ctx = execjs.compile(js_code)
print(ctx.call("add1", 1, 2))  # 输出: 3
print(ctx.eval('t1'))

执行

['abc', 'aaa', 'bbb']
3
aaaa

四,执行文件中的js代码:

text.js

var t=666
function add(a, b) {
    return a+b
}

 python

import execjs


# 读取js文件
def read_js_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as f:
        return f.read()

js_code2 = read_js_file('text.js')  # 假设norm.js中定义了add函数
print(js_code2)    # 查看js代码
ctx = execjs.compile(js_code2)
print(ctx.call("add", 2, 3))  # 输出: 5
print(ctx.eval('t'))    # 输出: 666

运行:

var t=666
function add(a, b) {
    return a+b
}

5
666

 

posted @ 2025-11-08 10:52  刘宏缔的架构森林  阅读(3)  评论(0)    收藏  举报