如何在 Ruby 中临时重定向 stderr? [英] How do I temporarily redirect stderr in Ruby?
问题描述
我想在块的持续时间内临时重定向 Ruby 脚本中的 stderr,确保在块的末尾将其重置为原始值.
I'd like to temporarily redirect stderr in a Ruby script for the duration of a block, ensuring that I reset it to its original value at the end of the block.
我在 ruby 文档中找不到如何执行此操作的问题.
I had trouble finding how to do this in the ruby docs.
推荐答案
在 Ruby 中,$stderr
指的是当前使用作为标准错误的输出流,而 STDERR
是默认 stderr 流.很容易将不同的输出流临时分配给 $stderr
.
In Ruby, $stderr
refers to the output stream that is currently used as stderr, whereas STDERR
is the default stderr stream. It is easy to temporarily assign a different output stream to $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
现在您可以执行以下操作:
Now you can do the following:
captured_output = capture_stderr do
# Does not output anything directly.
$stderr.puts "test"
end
captured_output
#=> "test\n"
同样的原理也适用于 $stdout
和 STDOUT
.
The same principle also works for $stdout
and STDOUT
.
这篇关于如何在 Ruby 中临时重定向 stderr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!