在node js中运行带有一些依赖项的python脚本

wyyhbhjk  于 2023-05-08  发布在  Python
关注(0)|答案(1)|浏览(111)

我有一个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);
    }
});

scripts.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

然后就停了未给出错误。如何运行完整的脚本?

wn9m85ua

wn9m85ua1#

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

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);
    }
  });

相关问题