0

I've noticed that when I spawn a python script in Node.js using the child_process spawn() method, I can't catch exceptions.

Here's a simple example to illustrate:

index.js:


const spawn = require('child_process').spawn;

(() => {
    const py = spawn('python', ['../pyfun/main.py']);

    py.stdout.on('data', function(data){
        console.log(data.toString());
    });

    py.stdout.on('end', function(){
        console.log('Finished');
    });

    py.stdout.on('error', function(){
        console.log('* Error');
    });

    py.on('error', (err) => {
        console.error('**', err);
    });

    py.stderr.on('error', (err) => {
        console.log('*** Error', error);
    })
})();

main.py:

def main():
    print('Hello')
    raise ValueError('Python Error')

if __name__ == '__main__':
    main()

The output is

Hello // <-- from python

Finished // <-- from Node

I'm getting the hello from the Python script, but I'm unable to pick up the error. This is also the case if I use raise Exception('error') in the python script too.

Any insight appreciated.

Sean
  • 2,609
  • 1
  • 18
  • 34
  • 1
    Add a handler for `py.on('exit', code => {})` and if the code is nonzero, the error has been dumped to stderr which you can access via `py.stderr.on('data', data => {})` – cbr Feb 13 '21 at 14:49
  • Thanks, adding 'stderr.on('data'... worked. If you add that as an answer I'll mark it as the answer. – Sean Feb 13 '21 at 14:55
  • Glad it worked! I'll do that. – cbr Feb 13 '21 at 14:59

1 Answers1

2

Add a handler for py.on('exit', code => {}) and if the code is nonzero, the error has been dumped to stderr which you can access via py.stderr.on('data', data => {})

cbr
  • 12,563
  • 3
  • 38
  • 63