利用Nodejs-express框架调取python脚本

1.使用child_process 子进程 中的 execFile

child_process 子进程 | Node.js v20 文档 (nodejs.cn)

官方文档

1-1安装child_process

复制代码
npm install child_process

1-2 在接口文件中使用

复制代码
var express = require('express');
var router = express.Router();
const { execFile } = require('child_process');  //导入execFile
const path = require('path');


/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});


// 访问index.html页面
router.get('/index.html', function (req, res) {
  // 将public下的index.html文件返回去
  res.sendFile(__dirname + '/index.html')
})

//调取python脚本
router.post('/python', function (req, res) {
  const testPyPath = path.resolve(__dirname, '../public/love.py');
  execFile('python', [testPyPath], (error, stdout, stderr) => {
    console.log(`Python script stdout: ${stdout}`);
    console.error(`Python script stderr: ${stderr}`);
    if (error) {
      console.error(`Python script failed: ${error}`);
      return res.status(500).send('Python script execution failed.');
    }

  })
  res.send({
    code: 200,
    msg: "Python脚本执行成功"
  });

});
module.exports = router;

execFile的第一个参数是Python解释器的路径(在大多数情况下,直接使用'python'即可),第二个参数是一个数组,包含了要执行的Python脚本的路径和传递给脚本的参数。

回调参数说明:

1)error:

类型:Error 对象或 null

描述:如果执行过程中发生错误(如脚本不存在、权限问题等),则此参数将包含一个错误对象。如果没有错误发生,则此参数为 null。

2)stdout:

类型:Buffer 或 string

描述:脚本的标准输出(stdout)。这通常是脚本执行过程中打印到控制台的文本。默认情况下,stdout 是一个 Buffer 对象,但如果你在 exec 或 execFile 方法中设置 encoding 选项为 'utf8',则 stdout 将是一个字符串。

3)stderr:

类型:Buffer 或 string

描述:脚本的标准错误输出(stderr)。这通常是脚本执行过程中打印的错误信息或警告。与 stdout 类似,stderr 默认是一个 Buffer 对象,但也可以设置为字符串。

我将调用的py文件放在了public下

2.在public文件夹下创建index.html 前端调用该接口

也可在前端框架中调用 这里为了测试方便就在index.html调用

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
      <button onclick="save()">保存</button>
</body>
<script type="text/javascript">
    function save() {
        fetch('http://127.0.0.1:3000/python', {
            method: 'POST'
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                console.log('调取成功');
            }
        })
        .catch(error => console.error('Error:', error));
    }

  </script>
</html>

3.py脚本示例,这里是画了一个简单的爱心,根据实际情况调用

复制代码
import turtle #导入turtle库
turtle.pensize(4)#设置画笔像素为4像素
turtle.pencolor("red")#设置画笔颜色为红色
turtle.fillcolor("pink")#设置填充颜色为粉红色
turtle.begin_fill()#开始填充
#开始绘制爱心
turtle.left(135)
turtle.forward(100)
turtle.circle(-50,180)#第一个半圆
turtle.left(90)
turtle.circle(-50,180)#第二个半圆
turtle.forward(100)
turtle.end_fill()#结束填充
turtle.done()
相关推荐
congvee3 天前
express学习第2期 - dotenv 加载配置文件
express
年纪轻轻就扛不住5 天前
Express 入门指南(超详细教程)
前端·前端框架·node.js·express·js
搞前端的小菜5 天前
从零实现一个GPT 【React + Express】--- 【4】实现文生图的功能
gpt·react.js·express
叫我菜菜就好5 天前
【node后端】搭建项目(Express+Ts+Typeorm+Mysql一步到位)
mysql·oracle·express
前端小盆友6 天前
从零实现一个GPT 【React + Express】--- 【5】实现网页生成能力
gpt·react.js·express
搞前端的小菜6 天前
从零实现一个GPT 【React + Express】--- 【2】实现对话流和停止生成
gpt·react.js·express
前端小盆友8 天前
从零实现一个GPT 【React + Express】--- 【4】实现文生图的功能
react.js·chatgpt·express
实习生小黄8 天前
express 连接在线数据库踩坑
node.js·express
搞前端的小菜8 天前
从零实现一个GPT 【React + Express】--- 【1】初始化前后端项目,实现模型接入+SSE
gpt·react.js·express
水冗水孚25 天前
express使用node-schedule实现定时任务,比如定时清理文件夹中的文件写入日志功能
javascript·node.js·express