gpt4 book ai didi

ruby - 如何在 Ruby 中临时重定向 stderr?

转载 作者:数据小太阳 更新时间:2023-10-29 06:22:31 25 4
gpt4 key购买 nike

我想在一个 block 的持续时间内在 Ruby 脚本中临时重定向 stderr,确保在 block 结束时将其重置为其原始值。

我在 ruby​​ 文档中找不到如何执行此操作。

最佳答案

在 Ruby 中,$stderr 指的是当前作为标准错误的输出流,而 STDERR默认 标准错误流。将不同的输出流临时分配给 $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"

同样的原则也适用于 $stdoutSTDOUT

关于ruby - 如何在 Ruby 中临时重定向 stderr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4459330/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com