强制Node.js刷新对子进程的写入 [英] Force Node.js to flush writes to child processes

查看:56
本文介绍了强制Node.js刷新对子进程的写入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我生成了一个这样的子进程:

I spawn a child process like this:

var child = require('child_process');
var proc = child.spawn('python', ['my_script.py', '-p', 'example']);

我还设置了一些数据处理:

I also set some data handling:

proc.stdin.setEncoding('utf8');
proc.stdout.setEncoding('utf8');
proc.stderr.setEncoding('utf8');

proc.stdout.on('data', function (data) {
  console.log('out: ' + data);
});

proc.stderr.on('data', function (data) {
  console.log('err: ' + data);
});

proc.on('close', function (code) {
  console.log('subprocess exited with status ' + code);
  proc.stdin.end();
});

我的Python脚本从 stdin 读取行,并且对每一行进行一些操作并打印到 stdout .它在Shell中工作正常(我写了一行,我立即获得了输出),但是当我在Node中这样做时:

My Python script reads lines from stdin and for each line does some operations and prints to stdout. It works fine in the shell (I write a line and I get the output immediately) but when I do this in Node:

for (var i = 0; i < 10; i++) {
  proc.stdin.write('THIS IS A TEST\n');
}

我什么也没得到.

我必须通过调用 proc.stdin.end()对其进行修复,但这也会终止子进程(我想保留在后台,以流式传输数据).

I got to fix it calling proc.stdin.end() but that also terminates the child process (which I want to stay in background, streaming data).

我还触发了一次刷新操作,用大量写操作填充了缓冲区,但这并不是一个选择.

I also triggered a flush filling the buffer with lots of writes, but that's not really an option.

有什么方法可以手动刷新流吗?

Is there any way to manually flush the stream?

推荐答案

您不会在print语句后刷新Python的输出.我有类似的问题,@ Alfe回答了我的问题.看看这个:

You are not flushing the output from Python after print statement. I had similar problem and @Alfe answered my question. Take a look at this:

以流模式输出流子进程

这篇关于强制Node.js刷新对子进程的写入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆