1

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

1 Answer 1

1
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

Sign up to request clarification or add additional context in comments.

1 Comment

Just to add I need to do let output = ""; to remove undefined.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.