我有一个Ruby脚本,它使用ERB类来解析一些嵌入式Ruby。如果被解析的代码重新定义了一个常量,那么ERB会向STDERR输出一个警告,但是我的脚本根本不知道这种情况发生了。
我可以在进入STDERR之前获取警告文本并进行操作/重定向吗?
#!/usr/bin/env ruby
require "erb"
begin
erb = ERB.new("<% FOO = 1 %>\n<%FOO = 2 %>", 0, "-")
result = erb.result
rescue
fail # Doesn't cause exception
end
STDOUT.puts "OKAY"
输出是:
(erb):2: warning: already initialized constant FOO
(erb):1: warning: previous definition of FOO was here
OKAY
答案 0 :(得分:0)
塞尔吉奥的小费让我有能力做我想做的事情:
captured_err = StringIO.new
old_stderr = $stderr
$stderr = captured_err
# Can generate warnings to $stderr
result = erb.result
$stderr = old_stderr
captured_err.close
if (captured_err.size != 0) then
STDERR.puts "** #####"
STDERR.puts "** ERROR: Ruby code resulted in warnings"
captured_err.string.each_line { |line| STDOUT.puts " " + line }
exit 1
end