Ruby打印输出到带有线程的文件

时间:2014-08-04 18:51:55

标签: ruby

我正在编写一个Ruby脚本,它循环遍历一些哈希并在哈希中执行命令,如此

$conf_info = {                                                                                                                                                            
"OpenSSH"   => {                                                                                                                                                      
    "type"  => "static",                                                                                                                                              
    "cmd"   => %q[sshd -T],                                                                                                                                           
    "msg"   => "Testing OpenSSH Configuration",                                                                                                                       
    "res"   => $cmd_results,                                                                                                                                          
    }
}

我有多个这些哈希值,我遍历所有哈希值,执行每个命令。我也在使用线程。问题是我无法输出到文件。我有这样的单独的线程。

threads = []                                                                                                                                                      
get_enums($options[:enumerate])                                                                                                                                   
threads << Thread.new {_run_($sys_info  , $options[:system]     , $enum_sys)   }                                                                                  
threads << Thread.new {_run_($net_info  , $options[:network]    , $enum_net)   }
threads.each {|t| t.join}

我输出到这样的文件

File.open("test_file", "w") do |file|                                                                                                                                     
    file.puts __start__
end

但是,文件只填充了这样的内容

#<Thread:0x98993fc>
#<Thread:0x9872fcc>

而不是程序的实际输出。我还需要程序输出到STDOUT和文件,也许有人请告诉我我可能做错了什么?

1 个答案:

答案 0 :(得分:0)

您无法通过将__start__的输出分配给变量来捕获其输出。您可以改为重定向输出:

使用TeeIO(根据this answer更新):

class TeeIO
  def initialize(*ios)
    ios.each{ |e| raise ArgumentError, "Not an IO object: #{e}" if not e.is_a? IO }
    @ios = ios
  end

  def write(data)
    @ios.each{ |io| io.write(data) }
  end

  def close
    @ios.each{ |io| io.close }
  end

  def flush
    @ios.each{ |io| io.flush }
  end

  def method_missing(meth, *args)
    # Return first if it's not an IO or else return self.
    first = @ios.map{ |io| io.send(meth, *args) }.first
    first.is_a? IO ? self : first
  end

  def respond_to_missing?(meth, include_all)
    @ios.all?{ |io| io.respond_to?(meth, include_all) }
  end
end

...

real_stdout = $stdout
file = File.open("test_file", "w")
$stdout = TeeIO.new(real_stdout, file)

__start__

$stdout = real_stdout
file.close