1. 安装execjs库
打开vscode,在终端窗口中输入安装命令:pip install pyexecjs2
2. 新建js文件
新建js文件js_demo1.js,编写被调用的函数,代码如下:
//定义函数
function concat_strs(s1,s2){
return s1 + s2;
}
const str1 = 'Hello ';
const str2 = 'world! ';
console.log(concat_strs(str1,str2)); //可以先运行本程序,测试函数功能
3. 在Python代码中调用js函数
新建py文件,代码如下:
import execjs #导入execjs
# 调用js文件中的函数,注意文件名和位置
res = execjs.compile(open('./js_demo1.js','r',encoding='utf-8').read()).call('concat_strs',"abc","def")
print(res)
运行py代码。