简体   繁体   English

读取正在等待输入的生成进程的stdout

[英]Read stdout of spawned process that is waiting for input

I have a Swift program that logs info to the stdout while waiting for a \\n (that terminates the execution). 我有一个Swift程序,它在等待\\n (终止执行)时将信息记录到stdout It requests the input immediately after start running and logs info 1~2 seconds after: 它在开始运行后立即请求输入并在以下情况后1~2秒记录信息:

fetchAndLogDataInBackground(); // will print some data in ~1 sec

readLine();

I'm spawn ing/ execFile ing it with the following: 我正在使用以下内容spawn / execFile

const spawn = require('child_process').spawn;

const process = spawn('swift/main');
process.stdout.on('data', data => console.log(data.toString()));

setTimeout(() => {
    process.stdin.write('\n');
}, 5000);

I was expecting to see the logs "live" since I'm using on('data') , but they are only being processed after the process.stdin.write('\\n'); 我希望看到日志“正常”,因为我正在使用on('data') ,但它们只是在process.stdin.write('\\n');之后process.stdin.write('\\n');

There's any way to get the data "live"? 有什么办法让数据“实时”?

PS: if I run the Swift program in terminal ( swift/main ), it works as expected. PS:如果我在终端( swift/main )中运行Swift程序,它会按预期工作。

You may have to either disable stdout buffering or manually flush stdout in Swift. 您可能必须禁用stdout缓冲或在Swift中手动刷新stdout。

To manually flush: 要手动清除:

fflush(__stdoutp)

To disable output buffering: 要禁用输出缓冲:

setbuf(__stdoutp, nil);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM