Reputation: 318
I am trying to run a python script with child_process
, I am testing with a simple script that prints hello
but the output I am getting back is undefinedhello
script.py
#!/usr/bin/python3
print ('hello')
app.js
router.get('/hello', (req, res) => {
const spawn = require('child_process').spawn;
const py = spawn('/usr/bin/python3', ['./python/script.py']);
let output;
py.stdout.on("data", (data) => {
output += data;
});
py.stdout.on("close", () => {
console.log(output);
res.sendStatus(200);
});
});
I have tried several suggestions but none have worked
Upvotes: 1
Views: 724
Reputation: 980
const spawn = require('child_process').spawn; // this should be out of the router
router.get('/hello', (req, res) => {
const py = spawn('/usr/bin/python3', ['./python/script.py']);
let output;
py.stdout.on("data", (data) => {
output += data.toString();
});
py.on("close", () => { // this differs
console.log(output);
res.sendStatus(200);
});
});
Reference child_process
Upvotes: 1