我有使用 Python 编写的自定义命令行,它使用“print”语句打印其输出。我通过生成一个子进程并使用 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);
现在的问题是我没有收到 flowing mode 中的输出.我想在打印后立即从子进程获取输出,但只有在子进程终止时(使用自定义 cli 的 quit 命令),我才会收到所有命令的输出。
最佳答案
您需要在子进程中刷新输出。
您可能认为这没有必要,因为当测试并让输出发生在终端上时,库会自行刷新(例如,当一行完成时)。打印到管道时不会这样做(由于性能原因)。
冲洗自己:
#!/usr/bin/env python
import sys, time
while True:
print "foo"
sys.stdout.flush()
time.sleep(2)
关于javascript - 流模式下的流子进程输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18849112/