每隔一秒从stdin读取一次

时间:2013-05-16 06:20:42

标签: ruby

我有两个简单的脚本,读者和作者:

writer.rb

while true
  puts "hello!"
  $stdout.flush
  sleep 1
end

reader.rb

while true
  puts "I read: #{$stdin.read}!"
  sleep 1
end

writer.rb不断写入stdout,reader.rb从stdin连续读取。

现在,如果我这样做:

ruby writer.rb | ruby reader.rb

我希望这能继续打印

I read: hello!
I read: hello!
I read: hello!

每隔一秒。但它只是阻止而不打印任何东西。如何打印?我认为writer.rb正在缓存输出,所以我添加了$stdout.flush,但这并没有让我在任何地方。

2 个答案:

答案 0 :(得分:3)

您必须使用$stdin.gets代替.read,因为.read读取到EOF。

puts "I read: #{$stdin.read}!"

应该是

puts "I read: #{$stdin.gets}!"

注意:这将包括换行符,因此输出将类似于:

I read: hello!
!
I read: hello!
!
I read: hello!
!

如果您不想使用尾随换行符,请使用$stdin.gets.chomp

使用$stdin.gets.chomp输出:

I read: hello!!
I read: hello!!

答案 1 :(得分:2)

我快速浏览了documentation of read,其中指出:

  

如果省略长度或为零,则读取直至EOF

在你的情况下,当编写器终止时发生,这预计永远不会发生。您可能希望使用readline

相关问题