有没有办法捕获警告,例如拯救异常?我不想简单地禁用警告(通过执行$VERBOSE = nil
),但希望在运行时捕获警告消息的内容。捕获警告消息
Q
捕获警告消息
1
A
回答
2
您可以重定向stderr
到StringIO对象捕捉字符串警告输出:
require 'stringio'
old_stderr = $stderr
$stderr = StringIO.new
Foo = 1
Foo = 2 # generates a warning
puts $stderr.string # prints the warning
$stderr = old_stderr
1
这是有点难看,因为你会被写入文件,你可能没有权限对其进行写操作,它将所有输出躲到$stderr
,不只是警告,但它的工作原理:
$stderr.reopen("errors.txt")
MyConst = 4
MyConst = 5 # generates a warning on the standard error output
$stderr.reopen("errors2.txt")
puts "The following errors happened:"
puts File.read("errors.txt")
2
require 'stringio'
def capture_stderr
old, $stderr = $stderr, StringIO.new
result = yield
[result, $stderr.string]
ensure
$stderr = old
end
相关问题
- 1. 警告消息
- 2. file_put_contents - 警告消息
- 3. ADBannerView警告消息
- 4. R2WinBUGS - 警告消息
- 5. 我的尝试捕获不显示警告消息
- 6. 通过psycopg2获取警告消息
- 7. iOS:CIColorKernel applyWithExtent警告消息
- 8. quantmod覆盖警告消息
- 9. NServiceBus回复消息警告
- 10. C#登录消息警告
- 11. CodeIgniter形式警告消息?
- 12. 编译器警告消息
- 13. 抑制gfortran警告消息
- 14. 警告消息Foundation 6
- 15. 警告消息更新
- 16. 警告消息scikit学习
- 17. 解决munmap警告消息
- 18. 弹出警告消息
- 19. 弹出警告消息asp.net
- 20. 弹出警告消息
- 21. Django形式警告消息
- 22. 捕获Win32消息
- 23. ImageMagick的 - 取消警告消息
- 24. Python xlrd:取消警告消息
- 25. 从aif web服务捕捉警告消息
- 26. g ++或gcc选项可以获得带有警告标识的警告消息
- 27. 无法提示javaFX中的信息消息或警告消息/
- 28. 如何捕获Windows消息?
- 29. 捕获所有Windows消息
- 30. 如何使用requiredMessage属性获取警告消息而不是错误消息?
是否可以重定向到一些Ruby的内部IO而不是外部文件? – sawa