红宝石管道,IO和stderr重定向 [英] ruby pipes, IO and stderr redirect

查看:87
本文介绍了红宝石管道,IO和stderr重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望有一个ruby程序(一个rake任务)观察另一个rake任务的输出.输出编写器输出到stderr.我想读那些话.我很难设置它.如果我有一个作家(stdout_writer.rb)不断打印出一些东西:

I am looking to have a ruby program (a rake task) observe an output from another rake task. The output writer outputs to stderr. I'd like to read those lines. I'm having difficulty setting it up. If I have a writer (stdout_writer.rb) that constantly prints something:

#!/usr/bin/env ruby
puts 'writing...'
while true
  $stdout.puts '~'
  sleep 1
end

和读取并回显的文件(stdin_reader.rb):

and a file that reads it and echoes (stdin_reader.rb):

#!/usr/bin/env ruby
puts 'reading...'
while input = ARGF.gets
  puts input
  input.each_line do |line|
    begin
      $stdout.puts "got line #{line}"
    rescue Errno::EPIPE
      exit(74)
    end
  end
end

我正在尝试让它们一起工作,什么也没发生:

and I'm trying to have them work together, nothing happens:

$ ./stdout_writer.rb 2>&1 | ./stdin_reader.rb
$ ./stdout_writer.rb | ./stdin_reader.rb

什么都没有...虽然我只是回声到stdin_reader.rb,但我得到了我期望的结果:

nothing... although if I just echo into stdin_reader.rb, I get what I expect:

piousbox@e7440:~/projects/opera_events/sendgrid-example-operaevent$ echo "ok true" | ./stdin_reader.rb
reading...
ok true
got line ok true
piousbox@e7440:~/projects/opera_events/sendgrid-example-operaevent$ 

那么我该如何设置一个将stderr插入其中的脚本,以便它可以逐行读取它?附加信息:这将是一个Ubuntu新贵服务script1.rb | script2.rb,其中script1发送消息,而script2验证消息是由script1发送的.

so how would I setup a script that gets stderr piped into it, so that it can read it line-by-line? Additional info: this will be an ubuntu upstart service script1.rb | script2.rb where script1 sends a message, and script2 verifies that the message was sent by script1

推荐答案

stdout_writer.rb的输出正由Ruby缓冲,因此阅读器进程看不到它.如果等待足够长的时间,您应该会看到结果以大块显示.

The output from stdout_writer.rb is being buffered by Ruby, so the reader process doesn’t see it. If you wait long enough, you should see the result appear in chunks.

您可以通过在stdout_writer.rb开始时在$stdout上将sync设置为true :

You can turn buffering off and get the result you’re expecting by setting sync to true on $stdout at the start of stdout_writer.rb:

$stdout.sync = true 

这篇关于红宝石管道,IO和stderr重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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