Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bidirectional communication with python-shell and node.js

I'm trying to communicate between node.js and python-shell. I was able to recieve data from 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 have communication in a chronolical way:

  1. recieve "data" from python
  2. send "go" to python
  3. recieve "data2" from python

Another Question: In the tutorial on https://github.com/extrabacon/python-shell it is written that you have to write pyshell.on() to wait for data while in the source-code the author writes pyshell.stdout.on(). Why is that?

Thanks!!! (wrong indention in python corrected)

like image 529
goetzmoritz Avatar asked Feb 22 '26 16:02

goetzmoritz


1 Answers

Your code exhibits some incorrect use of python-shell. Here below I have put together some notes. However, this is just what I primarily spot as mistakes so it will just rectify the use of the python-shell library but it might not necessarily remove all issues with your Python counterpart.


Incorrect use of stdout.on('data')

You appear to incorrectly utilize the event handler stdout.on. The handler takes "data" as argument denotes the event which happens when an output message is printed from Python script. This always be stdout.on('data') regardless what messages are printed.

This one is not valid:

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

It should always be

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

When relay a message to Python, you should enclose the command with end

You should change from:

pyshell.send('OK');

To this:

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

Therefore, rectifying those two mistakes, you 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);
 });
like image 151
TaoPR Avatar answered Feb 25 '26 06:02

TaoPR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!