1.PyExecJS
安装依赖
pip3 install PyExecJS
新建add.js文件
1 2 3
| function add(a,b){ return a+b; }
|
py文件去调用
1 2 3 4 5 6 7
| import execjs
with open('add.js', 'r', encoding='UTF-8') as f: js_code = f.read() context = execjs.compile(js_code) result = context.call("add", 2, 3) // 参数一为函数名,参数二和三为函数的参数 print(result)
|
运行结果:
2.js2py
#安装依赖库
pip3 install js2py
还是上面的add.js文件
python调用
1 2 3 4 5 6 7
| import js2py with open('add.js', 'r', encoding='UTF-8') as f: js_code = f.read() context = js2py.EvalJs() context.execute(js_code) result = context.add("1", "2") print(result)
|
3.Node.js
实际上是使用 Python 的os.popen执行 node 命令,执行 JS 脚本
首先,确保本地已经安装了 Node.js 环境
对js代码添加打印
1 2 3 4
| function add(a,b){ return Number(a)+Number(b); } console.log(add(process.argv[2], process.argv[3]));
|
用python调用控制台方式去使用
1 2 3 4 5 6
| import os nodejs = os.popen('node add.js '+'2'+' '+'3') m = nodejs.read() nodejs.close() print(m)
|
或者使用另一种方式
1 2 3 4 5 6 7 8 9 10
| function add(a,b){ return Number(a)+Number(b); }
module.exports.init = function (arg1, arg2) { console.log(add(arg1, arg2)); };
|
1 2 3 4 5
| import os cmd = 'node -e "require(\\"%s\\").init(%s,%s)"' % ('./add.js', 2, 3) pipeline = os.popen(cmd) result = pipeline.read() print(result)
|
4.node服务
用node做一个服务,提供api
还是add.js文件
1 2 3 4 5 6 7 8 9
| function add(a,b){ return Number(a)+Number(b); }
module.exports = { add: function (arg1, arg2) { return add(arg1, arg2); } };
|
新建add_api.js
下载 express 和 body-parser 两个包
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| var express = require('express') var app = express() var func = require('./add.js') var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
app.post('/add', function(req, res) { var ip = req.headers['x-real-ip'] ? req.headers['x-real-ip'] : req.ip.replace(/::ffff:/, ''); var time = new Date().toString().replace(/\+0800.*/, ''); console.log('INFO:', time, ip, req.method, req.originalUrl, '200 OK!'); let result = req.body; console.log("result: ", result); console.log("num1: ", result.num1); console.log("num2: ", result.num2);
var response = func.add(result.num1, result.num2); res.set('Content-Type', 'application/json') res.send(JSON.stringify({"result": response})); });
app.listen(8919, () => { console.log("开启服务,端口8919", new Date().toString().replace(/\+0800.*/, '')) })
|
运行,用python写个post请求
1 2 3
| import requests response = requests.post("http://127.0.0.1:8919/add", data={"num1": 2, "num2": 3}) print(response.text)
|
运行结果: