limegradient
limegradient

Reputation: 66

How can I integrate python with nodejs

I want to use python scripts with my Node.JS server, but whenever I run the node server, the python script doesn't run. It starts the server but no python runs. I think it's in this part of the code but I'm not exactly sure.

My index.js:

app.post("/readPython", (request, response) => {
 var dataToSend;
 const python = spawn('python', ['python/cookie.py'], "Kevin");

 python.stdout.on('data', function (data) {
  dataToSend = data.toString();
 });

 python.stderr.on('data', data => {
 console.error(`stderr: ${data}`);
 });

 python.on('exit', (code) => {
 console.log(`child process exited with code ${code}, ${dataToSend}`);
 response.sendFile(`${__dirname}/html/result.html`);
 });
});

My python script:

import sys

print("Hello World!")

sys.stdout.flush()

I don't know exactly what I should expect but whatever it is, the script isn't running. Any help?

Upvotes: 0

Views: 569

Answers (1)

Muhammad Abdullah
Muhammad Abdullah

Reputation: 322

the 3rd argument (options) in spawn() should be an object. I am assuming you are trying to send Kevin as argument. It should be like

const python = spawn('python', ['helloworld.py',"Kevin"]);

python.stdout.on('data', (data)=> {

        console.log(data.toString());
       
    });

Upvotes: 1

Related Questions