Dan Dan - 11 months ago 64
Python Question

Bidrectional node/python communication

I'm trying to implement simple bidirectional communication between node and a spawned Python process.


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;
child.stdin.write("i = " + i++ + "\n");
}, 1000);

on Python forces unbuffered I/O so I would expect to see the output (I've also tried
) but don't. I know I can use
but that prevents me from writing data later.

Answer Source

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