Bidrectional节点/ python通信

我正试图在节点和派生的Python进程之间实现简单的双向通信。

python:

import sys for l in sys.stdin: print "got: %s" % l 

节点:

 var spawn = require('child_process').spawn; var child = spawn('python', ['-u', 'ipc.py']); child.stdout.on('data', function(data){console.log("stdout: " + data)}); var i = 0; setInterval(function(){ console.log(i); child.stdin.write("i = " + i++ + "\n"); }, 1000); 

在Python上使用-u强制unbuffered I / O,所以我期望看到输出(我也尝试了sys.stdout.flush() ),但没有。 我知道我可以使用child.stdout.end()但是这阻止了我以后写数据。

您的Python代码与TypeError: not all arguments converted during string formatting崩溃TypeError: not all arguments converted during string formatting

 print "got: " % l 

你应该写

 print "got: %s" % l 

你可以看到Python输出的错误:

 var child = spawn('python', ['-u', 'ipc.py'], { stdio: [ 'pipe', 'pipe', 2 ] }); 

在Node.js上,也就是仅pipe道标准输出,但让标准错误进入节点的stderr。


即使有这些修复,甚至会占用-u sys.stdin.__iter__将被缓冲 。 要解决它,请使用.readline

 for line in iter(sys.stdin.readline, ''): print "got: %s" % line sys.stdout.flush()