我想在一个块的持续时间内临时重定向 Ruby 脚本中的 stderr,确保在块结束时将其重置为其原始值。
我很难在 ruby 文档中找到如何做到这一点。
在红宝石中,$stderr
指的是输出流目前使用的作为标准错误,而STDERR
is the default标准错误流。可以很容易地临时分配不同的输出流$stderr
.
require "stringio"
def capture_stderr
# The output stream must be an IO-like object. In this case we capture it in
# an in-memory IO object so we can return the string value. You can assign any
# IO object here.
previous_stderr, $stderr = $stderr, StringIO.new
yield
$stderr.string
ensure
# Restore the previous value of stderr (typically equal to STDERR).
$stderr = previous_stderr
end
现在您可以执行以下操作:
captured_output = capture_stderr do
# Does not output anything directly.
$stderr.puts "test"
end
captured_output
#=> "test\n"
同样的原理也适用于$stdout
and STDOUT
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)