利用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()
相关推荐
一个很帅的帅哥1 天前
实现浏览器的下拉加载功能(类似知乎)
开发语言·javascript·mysql·mongodb·node.js·vue·express
QQ13049796942 天前
Vue+nodejs+express旅游景区门票预订网站的设计与实现 8caai前后端分离
vue.js·express·旅游
qq22951165022 天前
python毕业设计基于django+vue医院社区医疗挂号预约综合管理系统7918h-pycharm-flask
前端·vue.js·express
闲来无事垂钓8 天前
Node.js学习记录(二)
node.js·接口·express·路由·跨域·cors·jsonp
wxin_VXbishe10 天前
springboot高校兼职平台-计算机毕业设计源码65602
java·spring boot·python·struts·spring·django·express
读心悦10 天前
使用脚手架来创建 express 项目
express
N1cez16 天前
IEEE PDF eXpress 报错解决 Error in converting file + font not embedded
pdf·express
problc17 天前
腾讯开源突破技术:V-Express引领人像照片视频化新潮流
音视频·express
GDAL18 天前
Express与SQLite集成教程:轻松实现数据库操作
数据库·sqlite·express
GDAL20 天前
Express Response类深度解析:全面掌握属性与方法,提升开发效率
node.js·express