ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

python:python执行js

2026/8/5 12:52:16 拓冰建站 浏览量
python:python执行js

一,安装node

安装Node.js(推荐)

    • 下载地址:https://nodejs.org
    • 验证安装:node -v
$ node -v
v22.20.0

二,安装python库

$ pip install PyExecJS
Collecting PyExecJSDownloading PyExecJS-1.5.1.tar.gz (13 kB)Installing build dependencies ... doneGetting requirements to build wheel ... donePreparing 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: PyExecJSBuilding wheel for PyExecJS (pyproject.toml) ... doneCreated wheel for PyExecJS: filename=pyexecjs-1.5.1-py3-none-any.whl size=14649 sha256=19677164f4303803756805f1a29a6bcd66ff7fa5f4d21b66ea740d25a1d836fbStored 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