问题描述
我正在使用 popen3
运行一个进程,并尝试读取stdout流。我希望能够检测每个字符,因为它被放入stdout,但即使使用 stdout.getc
,我只能在有换行符时获得任何输出。
I'm running a process using popen3
, and trying to read the stdout stream. I want to be able to detect each character as it's put into stdout, but even using stdout.getc
, I'm only able to get any output once there's a newline.
任何提示?我已经看到这回答了 stdin.getc
,但不是stdout。
Any tips? I've seen this answered with stdin.getc
, but not stdout.
推荐答案
你遇到的问题是大多数程序在通过管道运行时,这是用 popen
进行的,将使用缓冲输出运行。
The problem you have is that most programs when run through a pipe, which is what happens with popen
, will be run using buffered output.
但你要找的是无缓冲输出。只有当proccess附加到PTY时才会发生无缓冲输出。即如地狱。
But what you are looking for is unbuffered output. Unbuffered output only happens when the proccess is attached to a PTY. I.e. a shell.
当您将进程附加到管道时,输出将被缓冲,除非进程在其中显式调用 flush
输出处理。
When you attach the process to a pipe the output will be buffered unless the process is explicitly calling flush
during its output processing.
您有几个选择:
-
如果您可以控制使用
popen
运行的源代码,然后在每个输出序列后强制在stdout上调用flush
。
If you have control over the source code that you run with
popen
then force aflush
call on stdout after each output sequence.
您可以尝试在 stdbuf -o0
下运行命令,该命令会尝试强制执行无缓冲输出。
看到这个答案:
。
但是不能保证不适用于所有程序。
You could try and run the command under stdbuf -o0
, which tries to force unbuffered output.
See this answer:
Force line-buffering of stdout when piping to tee.
However that is not guaranteed to work for all programs.
您可以尝试使用Ruby PTY
库而不是 popen
来制作程序在伪终端下运行,因此运行无缓冲。看到这个答案:
You could try to use the Ruby PTY
library instead of popen
to make the program run under a pseudo-terminal, and hence run unbuffered. See this answer:
Continuously read from STDOUT of external process in Ruby
选项3最有可能与任何您希望运行和监控的程序,而其他选项可能会或可能不会起作用,具体取决于您运行的程序以及您是否有权访问该程序的源代码。
Option 3 is most likely to work with any program you want to run and monitor, while the other options may or may not work depending on the program you are running and if you have access to the source code of that program.
这篇关于如何在Ruby中使用Open#popen3读取未缓冲的stdout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!