Reputation: 2804
I'm trying to implement simple bidirectional communication between node and a spawned Python process.
Python:
import sys
for l in sys.stdin:
print "got: %s" % l
Node:
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);
Using -u
on Python forces unbuffered I/O so I would expect to see the output (I've also tried sys.stdout.flush()
) but don't. I know I can use child.stdout.end()
but that prevents me from writing data later.
Upvotes: 2
Views: 1681
Reputation: 133998
Your Python code crashes with TypeError: not all arguments converted during string formatting
at line
print "got: " % l
You ought to write
print "got: %s" % l
You can see the errors that Python outputs by doing:
var child = spawn('python', ['-u', 'ipc.py'],
{ stdio: [ 'pipe', 'pipe', 2 ] });
on Node.js, that is, pipe only standard output but let the standard error go to Node's stderr.
Even with these fixes, and even accounting for -u
the sys.stdin.__iter__
will be buffered. To work around it, use .readline
instead:
for line in iter(sys.stdin.readline, ''):
print "got: %s" % line
sys.stdout.flush()
Upvotes: 1