使用python shell和node.js进行双向通信

bidirectional communication with python-shell and node.js

本文关键字:双向通信 js node python shell 使用      更新时间:2023-09-26

我正在尝试在node.js和python shell之间进行通信。我能够从python shell对象接收数据,但当我试图向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');
});

和我的测试.py:

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

我基本上想以时间的方式进行交流:

  1. 从python接收"数据">
  2. 将"go"发送到python
  3. 从python接收"data2">

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

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

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


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

您似乎未正确使用事件处理程序stdout.on。处理程序将";数据";as参数表示从Python脚本打印输出消息时发生的事件。无论打印的消息是什么,这始终是stdout.on('data')

这个无效

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

它应该始终是

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

将消息中继到Python时,应将命令与end一起包含

您应该从以下位置更改:

pyshell.send('OK');

对此:

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

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

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);
 });