利用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 天前
Node.js: express 使用 Open SSL
express
不写八个6 天前
Express教程【006】:使用Express写接口
express
課代表6 天前
Adobe LiveCycle ES、LiveCycle DS 与 BlazeDS 关系解析与比较
数据库·adobe·pdf·express·livecycle·lcds·soa平台
不写八个9 天前
Express教程【002】:Express监听GET和POST请求
前端·javascript·express
不写八个9 天前
Express教程【003】:Express获取查询参数
开发语言·express
爱编程的小学究12 天前
【node】Express创建服务器
运维·服务器·express
码农捻旧14 天前
基于GitHub Actions+SSH+PM2的Node.js自动化部署全流程指南
node.js·自动化·ssh·github·express
漫谈网络15 天前
基于TypeScript的全栈待办事项应用Demo
前端·javascript·typescript·node.js·express
xx240616 天前
什么是Express
express
码农捻旧18 天前
Node.js Express 项目现代化打包部署全指南
javascript·node.js·github·express