利用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()
相关推荐
水冗水孚3 天前
告别黑盒!手写Windows版简易NodeMON,学习文件监听代码修改与进程服务重启知识
node.js·express
天意pt4 天前
Blog-SSR 系统操作手册(v1.0.0)
前端·vue.js·redis·mysql·docker·node.js·express
漫游嵌入式7 天前
《PCI EXPRESS体系结构导读》---(5)PCI总线Device号的分配
express·pcie·pci
漫游嵌入式7 天前
《PCI EXPRESS体系结构导读》---(4)PCI总线Bus号初始化
express·pcie·pci
HWL56798 天前
Express图片上传功能,包括数据库存储
express
小新1109 天前
后台nodejs+express从sql server中获取数据
express·mssql
漫游嵌入式11 天前
《PCI EXPRESS体系结构导读》---(1)基本概念
express·pcie·pci
C_心欲无痕11 天前
nodejs - express:流行的 Web 应用框架
前端·node.js·express
1024小神11 天前
Express.js中间件Middleware是处理 HTTP 请求和响应以及jwt token认证
http·中间件·express
小新11014 天前
vscode+nodejs+express 搭建一个简单网站
vscode·node.js·express