节点 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 脚本
发布评论