在节点 js 中运行具有某些依赖项的 python 脚本

编程入门 行业动态 更新时间:2024-10-05 17:25:20

在<a href=https://www.elefans.com/category/jswz/34/1771452.html style=节点 js 中运行具有某些依赖项的 python 脚本"/>

在节点 js 中运行具有某些依赖项的 python 脚本

我有一个 python 脚本来排序 pdf/docx 文件并将它们保存到相应的文件夹中。该脚本在独立模式下运行良好。

我想将其集成到我现有的 nodejs 服务器中。我正在使用子进程。但问题是每当我运行文件时它都会停止。也不给出任何错误。如果我不导入任何内容,那么文件会显示输出。但是当我导入依赖项时,文件会在那一行停止运行

app.get("/test", (req, res) => {
  var dataToSend;

  try {
    
      // spawn new child process to call the python script
      const python = spawn("python3", [path.join(__dirname, "./scripts/script.py")]);

      // collect data from script
      python.stdout.on("data", function (data) {
          console.log("Pipe data from python script ...");
          dataToSend = data.toString();
        });
        // in close event we are sure that stream from child process is closed
        python.on("close", (code) => {
            console.log(`child process close all stdio with code ${code}`);
            // send data to browser
            res.send(dataToSend);
        });
    } catch (error) {
        res.send(error.message);
    }
});

脚本.py:

import os

# Define the input and output directories
input_dir = './sampleResumes'
output_dir = './output'

print("Work started ")
print("input_dir -------- ", os.listdir(input_dir))

我得到的输出:

Work started

然后它停止了。没有给出错误。我怎样才能运行完整的脚本?

回答如下:

使用绝对路径解决了我的问题:

app.get("/test", (req, res) => {
    var dataToSend;
  
    try {
      
      const scriptPath = path.join(__dirname, "./scripts/segment.py");
      const scriptDir = path.dirname(scriptPath);
  
      
      process.chdir(scriptDir);
  
      const python = spawn("python3", [scriptPath]);
  
      python.stdout.on("data", function (data) {
        console.log("Pipe data from python script ...");
        dataToSend = data.toString();
      });
  
 
      python.on("close", (code) => {
        console.log(`child process close all stdio with code ${code}`);
  
        res.send(dataToSend);
      });
    } catch (error) {
      res.send(error.message);
    }
  });

更多推荐

在节点 js 中运行具有某些依赖项的 python 脚本

本文发布于:2024-05-30 20:03:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1770869.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:节点   脚本   js   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!