Bi-directional communication with python shell and node.js

I am trying to establish communication between node.js and python-shell. I was able to get data from the python-shell object, but when I try to send a message to the python shell, it crashes.

my app.js:

var PythonShell = require('python-shell');

var options = {
    scriptPath: '/home/pi/python'
};

var pyshell = new PythonShell('test.py', options, {
    mode: 'text'
});

pyshell.stdout.on('data', function(data) {
    pyshell.send('go');
    console.log(data);
});

pyshell.stdout.on('data2', function(data) {
    pyshell.send('OK');
    console.log(data);
});

pyshell.end(function(err) {
    if (err) throw err;
    console.log('End Script');
});

      

and my test.py:

import sys
print "data"
for line in sys.stdin:
    print "data2"

      

I basically want to communicate in chronological order:

  • get "data" from python
  • send "go" to python
  • get "data2" from python

Another question: The tutorial on https://github.com/extrabacon/python-shell says that you need to write pyshell.on () to wait for data, and in the source code, the author writes pyshell.stdout.on (). Why is this?

Thank!!! (fixed wrong fix in python)

+3


source to share


1 answer


There is a misuse in your code python-shell

. Below I have collected a few notes. However, this is exactly what I perceive as bugs in the first place, so it will just fix the use of the library python-shell

, but may not necessarily remove all problems with your Python partner.




Incorrect use of stdout.on ('data')

You are using your event handler incorrectly stdout.on

. The handler takes "data" because the argument denotes an event that occurs when the output message is printed from the Python script. This will always be the case stdout.on('data')

no matter what messages are printed.

This is not true:

pyshell.stdout.on('data2', function(data) { .... })

      

It should always be

pyshell.stdout.on('data', function(data) { .... })

      




When passing a message to Python, you must enclose the command end

You should change:

pyshell.send('OK');

      

For this:

pyshell.send('OK').end(function(err){
    if (err) handleError(err);
    else doWhatever();
})

      




Therefore, correcting these two errors, the code should become:

pyshell.stdout.on('data', function(data) {
    if (data == 'data') 
        pyshell.send('go').end(fucntion(err){
            if (err) console.error(err);
            // ...
        });
    else if (data == 'data2')
        pyshell.send('OK').end(function(err){
            if (err) console.error(err); 
            // ...
        });
    console.log(data);
 });

      

+2


source







All Articles