codebot
codebot

Reputation: 707

Cannot execute python with node exec

Using node's child-spawn exec basically mimics the shell, so I should be able to do

exec('python' , (error, stdout, stderr) => { 
  if (error || stderr) {
    console.log('exec error ' , error )
    console.log('exec stderr ' ,  stderr)
  } else {
    console.log('exec output ' , stdout)
  }
})  

or

exec('python hello.py' , (error, stdout, stderr) => { 
  //same as above

but I get nothing back, not even errors.

What am I missing here ?

Thanks

Upvotes: 0

Views: 81

Answers (1)

antonku
antonku

Reputation: 7675

python command expects some data to be written to stdin. You can write that data by using the subprocess object returned by exec:

const { exec } = require('child_process');

const subprocess = exec('python' , (error, stdout, stderr) => {
  if (error || stderr) {
    console.log('exec error ' , error )
    console.log('exec stderr ' ,  stderr)
  } else {
    console.log('exec output ' , stdout)
  }
})

subprocess.stdin.write('print("test");');
subprocess.stdin.end()

Probably hello.py also waits for some data.

Upvotes: 2

Related Questions