PyExecJS
简介
PyExecJS 是一个可以使用 Python 来模拟运行 JavaScript 的库。
使用该模块可以通过python程序调用执行js代码,获取js代码返回的结果!
注意事项:电脑必须安装好了nodejs开发环境上述模块才可以生效!
环境安装:pip install PyExecJS
使用步骤:
# 1.导包
import execjs
# 2.创建node对象
node = execjs.get()
# 3.编译js文件返回上下文ctx对象(将js文件中的代码读取出来,被compile进行编译)
fp = open('test.js','r',encoding='utf-8')
ctx = node.compile(fp.read())
# 4.使用上下文对象ctx调用eval函数执行js文件中的指定函数即可
result = ctx.eval('getPwd("123456")')
# 或者调用call函数执行js文件中的指定函数
# result = ctx.call("getPwd", "123456")
print(result)
# 简写
js_compile = execjs.compile(open('test.js', 'r', encoding='utf-8').read())
result = js_compile.call("getPwd", '123456')示例JS代码:
// test.js
function getPwd(pwd) {
return pwd;
}Windows导包
Windows 系统直接导包会报错,需使用以下代码进行导包
import subprocess
from functools import partial
subprocess.Popen = partial(subprocess.Popen, encoding="UTF-8")
import execjsLast updated