捕获警告消息 [英] Capturing warning messages
本文介绍了捕获警告消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法捕捉警告,比如拯救异常?我不想简单地禁用警告(通过执行 $VERBOSE = nil
),而是想在运行时捕获警告消息的内容.
Is there a way to capture the warnings, something like rescue for exceptions? I do not want to simply disable the warnings (by doing $VERBOSE = nil
) but want to capture the content of the warning messages during run time.
推荐答案
您可以将 stderr
重定向到 StringIO 对象以捕获字符串中的警告输出:
You can redirect stderr
to a StringIO object to capture the warnings output in a string:
require 'stringio'
old_stderr = $stderr
$stderr = StringIO.new
Foo = 1
Foo = 2 # generates a warning
puts $stderr.string # prints the warning
$stderr = old_stderr
这篇关于捕获警告消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文