与 python-shell 和 node.js 的双向通信

goe*_*itz 3 javascript python node.js

我正在尝试在 node.js 和 python-shell 之间进行通信。我能够从 python-shell-object 接收数据,但是当我尝试向 python-shell 发送消息时,它崩溃了。

我的 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');
});
Run Code Online (Sandbox Code Playgroud)

和我的 test.py:

import sys
print "data"
for line in sys.stdin:
    print "data2"
Run Code Online (Sandbox Code Playgroud)

我基本上想按时间顺序进行交流:

  1. 从python接收“数据”
  2. 发送“去”到python
  3. 从python接收“data2”

另一个问题:在https://github.com/extrabacon/python-shell上的教程中写道,您必须编写 pyshell.on() 以等待数据,而在源代码中作者编写 pyshell.stdout。在()。这是为什么?

谢谢!!!(纠正了python中的错误缩进)

Tao*_*oPR 5

您的代码显示了一些不正确的python-shell. 下面我整理了一些笔记。然而,这正是我主要发现的错误,因此它只会纠正python-shell库的使用,但不一定能消除与 Python 对应的所有问题。


stdout.on('data') 的错误使用

您似乎错误地使用了事件处理程序stdout.on。处理程序将“数据”作为参数表示从 Python 脚本打印输出消息时发生的事件。stdout.on('data')无论打印什么消息,这始终是。

这是无效的

pyshell.stdout.on('data2', function(data) { .... })
Run Code Online (Sandbox Code Playgroud)

它应该总是

pyshell.stdout.on('data', function(data) { .... })
Run Code Online (Sandbox Code Playgroud)

将消息中继到 Python 时,您应该将命令包含在 end

你应该从:

pyshell.send('OK');
Run Code Online (Sandbox Code Playgroud)

对此:

pyshell.send('OK').end(function(err){
    if (err) handleError(err);
    else doWhatever();
})
Run Code Online (Sandbox Code Playgroud)

因此,纠正这两个错误,你的代码应该变成:

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);
 });
Run Code Online (Sandbox Code Playgroud)