stream式传输子stream程输出

我有用Python编写的自定义命令行,使用“print”语句打印输出。 我通过产生一个subprocess并使用child.stdin.write方法向它发送命令从Node.js使用它。 来源:

var childProcess = require('child_process'), spawn = childProcess.spawn; var child = spawn('./custom_cli', ['argument_1', 'argument_2']); child.stdout.on('data', function (d) { console.log('out: ' + d); }); child.stderr.on('data', function (d) { console.log('err: ' + d); }); //execute first command after 1sec setTimeout(function () { child.stdin.write('some_command' + '\n'); }, 1000); //execute "quit" command after 2sec //to terminate the command line setTimeout(function () { child.stdin.write('quit' + '\n'); }, 2000); 

现在的问题是我没有在stream动模式下接收输出。 我想从打印的subprocess中获得输出,但是只有当subprocess终止时(使用自定义cli的quit命令),我才接收所有命令的输出。

您需要刷新subprocess中的输出。

可能你认为这不是必须的,因为当testing并让输出发生在terminal上时,库自己刷新(例如当一行完成时)。 当打印进入pipe道时(由于性能原因),这不会完成。

冲洗自己:

 #!/usr/bin/env python import sys, time while True: print "foo" sys.stdout.flush() time.sleep(2) 

最好的方法是使用python标准输出的非缓冲模式。 它将强制python写输出到输出stream,而不需要刷新自己。

例如:

 var spawn = require('child_process').spawn, child = spawn('python',['-u', 'myscript.py']); // Or in custom_cli add python -u myscript.py child.stdout.on('data', function (data) { console.log('stdout: ' + data); }); child.stderr.on('data', function (data) { console.log('stderr: ' + data); });