javascript - 流模式下的流子进程输出

标签 javascript python node.js

我有使用 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/

相关文章:

javascript - 是否有支持递归之类的javascript模板引擎?

javascript - grunt js 缩小转换 unicode 字符

javascript - Ajax 请求未提供任何数据

python - 在 NumPy 和 Python 中使用类似 R 或类似 MATLAB 的语法更新子矩阵

node.js - Socket.io 通过 id 断开客户端

javascript - 你能撤消 lerna bootstrap 吗?

javascript - 如何获取使用浏览按钮选择的文件的内容?

Python "IOError: [Errno 21] Is a directory: '/home/thomasshera/Pictures/Star Wars'"

node.js - path.join vs path.resolve with __dirname

node.js - 安装 Node 包时出错