利用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()
相关推荐
码农捻旧2 分钟前
解决Mongoose “Cannot overwrite model once compiled“ 错误的完整指南
javascript·数据库·mongodb·node.js·express
HWL56791 天前
Express项目解决跨域问题
前端·后端·中间件·node.js·express
程序员拂雨3 天前
Express知识框架
node.js·express
layman05285 天前
node.js 实战——餐厅静态主页编写(express+node+ejs+bootstrap)
node.js·bootstrap·express
layman05287 天前
node.js 实战——express图片保存到本地或服务器(七牛云、腾讯云、阿里云)
node.js·express
小妖66610 天前
express 怎么搭建 WebSocket 服务器
websocket·网络协议·express
一袋米扛几楼9817 天前
【前端】从零开始的搭建顺序指南(技术栈:Node.js + Express + MongoDB + React)book-management
前端·node.js·express
layman052817 天前
node.js 实战——从0开始做一个餐厅预订(express+node+ejs+bootstrap)
node.js·express
白昼的星光@18 天前
使用nodeJs的express+axios+cors做代理
express
键盘飞行员19 天前
使用 Node、Express 和 MongoDB 构建一个项目工程
数据库·mongodb·express