Ruby 中的输出重定向故障排除

Output redirection troubleshooting in Ruby

所以我正在尝试将输出临时重定向到一个文件:

  prev_std = STDOUT

  $stdout.reopen(@filename, 'w:UTF-8')

  # stuff happens here with @filename and lots of output

  $stdout = prev_std

但是当我这样做时,似乎我之后无法将其重定向回来。我在这里做错了什么?

您在 STDOUT 上调用 reopen,因为 $stdout 只是一个指向同一对象的全局变量。这将永久更改 STDOUT.

这个怎么样:

$stdout = File.open(@filename, 'w:UTF-8')

# ...

$stdout = prev_std

STDOUT是代表标准输出的常量,是一个IO对象。而$stdout是一个全局变量,其默认值通常是STDOUT本身,默认情况下,两者都指向同一个对象:

$stdout.object_id == STDOUT.object_id => true

如果您在其中一个上调用方法,另一个将受到影响。因此,如果您使用 $stdout 调用方法,它也会对 STDOUT 生效。在 $stdout 上调用 reopen 也会影响 STDOUT(即使它是一个常量)。

如果您想暂时将输出重定向到一个文件,然后将其恢复到标准输出,您应该分配 $stdout 一个新的 IO 对象:

$stdout = File.open('/path/to/file', 'w:UTF-8')
puts "this will go to the file"
$stdout = STDOUT
puts "this will go to standard output!"

另请参阅以下问题:

  • What is the difference between Ruby's $stdout and STDOUT?
  • What is the difference between STDIN and $stdin in Ruby?
  • Reopening an IO Stream vs. just using the new Stream
  • The IO reopen method 以及其余的 IO 方法。