Node.js运行Python脚本

在项目中遇到的问题,记录下来,方便日后查阅和复习

python-shell 一种从Node.js运行Python脚本的简单方法,它具有基本但有效的进程间通信和更好的错误处理能力。pythonshell官网

要求

首先,请确保您能够从终端运行python3(Mac / Linux)或python(Windows)。如果不是,则可能需要将其添加到PATH。如果要使用不在PATH中的python版本,则应指options.pythonPath
需要有node环境,安装相关包。

安装

npm install python-shell

node调用python代码

var express = require("express");
var bodyParser = require("body-parser");
var app = express();
var https = require("https");
const { PythonShell } = require("python-shell");
var base64 = require("base-64");
var utf8 = require("utf8");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

const data = [{"browser_open":"\"http://www.bilibili.com\""}]
// 测试automagica
app.post("/automagica", (req, res, next) => {
  console.log(req.body, "req.body");
  var bytes = utf8.encode(JSON.stringify(data)); // req.body
  var encoded = base64.encode(bytes);
  let options = {
    pythonPath: "/usr/local/bin/python3",
    args: ["-d",encoded],
  };
  console.log(options.args, "data");
  PythonShell.run("tmp.py", options, function (err, result) {
    if (err) throw err;
    console.log("result: ", result.toString());
    res.send(result.toString());
  });
});
var server = app.listen(3010, "localhost", function () {
  var host = server.address().address;
  var port = server.address().port;
  console.log("running on host " + host + ", listening to port " + port);
  console.log("应用实例,访问地址为 http://%s:%s", host, port);
});

前端接口调用代码

function demo() {
  const params = {
    browser_open: "www.baidu.com",
  };
  fetch(baseURL + "automagica", {
    method: "post",
    headers: {
      "Content-type": "application/json",
    },
    body: JSON.stringify(params),
  })
    .then(function (data) {
      return data.json();
    })
    .then(function (data) {
      console.log(data, "HHHHHHH");
    });
}

你可能感兴趣的:(Node.js运行Python脚本)