如何在不读取IO的情况下知道IO是否为空? [英] How can I know if an IO is empty without reading it?
问题描述
我有一个 IO
对象(比如 $ stdout
, $ stderr
)。我可以在它上面执行 read.empty?
来查看它是否为空,但是如果没有读取它是否可以知道它是否为空?我知道文件
有大小
,但是 IO
没有。
I have an IO
object (like $stdout
, $stderr
). I can do read.empty?
on it to see if it is empty, but is it possible to know if it is empty without reading it? I know that File
has size
, but IO
does not.
编辑
如果我的问题不够明确,很抱歉。我从 Open3.popen3
获取这些对象作为返回值。我想看看是否有任何内容写入标准错误,例如。如果可能的话,我想在不阅读的情况下这样做。
Edit
Sorry if my question was not clear enough. I get these objects as return values from Open3.popen3
. I want to see if anything was written to the standard error, for example. And I want to do it without reading it if possible.
推荐答案
这是 IO :: select 方法:
编辑问题后的更新示例:
Updated example after question edited:
require 'open3'
select_timeout = Rational(1,10) # optional
Open3.popen3('ls /') do
|stdin, stdout, stderr, w_thread|
rdin, rdout, rderr = IO.select([stdin], [stdout], [stderr], select_timeout)
if rdin
p 'no data on standard input' unless rdin.member? stdin
p 'no data on standard output' unless rdout.member? stdout
p 'no data on standard error' unless rderr.member? stderr
else
p 'none of streams has data available'
end
retval = w_thread.value
end
# "no data on standard output"
# "no data on standard error"
而只有标准输入包含数据来自衍生线程命令 ls /
Whereas only standard input contains data from spawned thread command ls /
这篇关于如何在不读取IO的情况下知道IO是否为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!