-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpythonExecutor.js
34 lines (28 loc) · 921 Bytes
/
pythonExecutor.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
const { spawn } = require('child_process');
// Function to execute the Python script and return the response as JSON
function executePythonScript(scriptPath, args) {
return new Promise((resolve, reject) => {
const pythonProcess = spawn('python3', [scriptPath, ...args]);
let result = '';
let error = '';
pythonProcess.stdout.on('data', (data) => {
result += data.toString();
});
pythonProcess.stderr.on('data', (data) => {
error += data.toString();
});
pythonProcess.on('close', (code) => {
if (code === 0) {
try {
const jsonData = JSON.parse(result);
resolve(jsonData);
} catch (err) {
reject('Invalid JSON response from the Python script.');
}
} else {
reject(`Python script execution failed with code: ${code}, Error: ${error}`);
}
});
});
}
module.exports = executePythonScript;