将全局$ stdout重新分配给控制台-ruby [英] Reassigning global $stdout to console - ruby

查看:76
本文介绍了将全局$ stdout重新分配给控制台-ruby的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将$ stdout设置为临时写入文件,然后再返回文件.

I am trying to set $stdout to write to a file temporarily and then back to a file.

test.rb :
   old_stdout = $stdout    
    $stdout.reopen("mytestfile.out",'w+')
       puts "this goes in mytestfile"
    $stdout= old_stdout
puts "this should be on the console"
    $stdout.reopen("mytestfile1.out",'w+')
       puts "this goes in mytestfile1:"
    $stdout = old_stdout
 puts "this should be back on the console"

这是输出.

ruby test.rb => no output on the console
cat mytestfile.out 
  this goes in mytestfile
  this should be on the console
cat  mytestfile1.out
  this goes in mytestfile1:
  this should be back on the console

我不确定为什么$ stdout没有重置为控制台?

I am not sure why $stdout is not getting reset to console ?

推荐答案

可以通过调用

This problem can be resolved by calling dup on $stdout before changing it:

old_stdout = $stdout.dup  
$stdout.reopen("mytestfile.out",'w+')
puts "this goes in mytestfile"
$stdout = old_stdout.dup
puts "this should be on the console"
$stdout.reopen("mytestfile1.out",'w+')
puts "this goes in mytestfile1:"
$stdout = old_stdout
puts "this should be back on the console"

输出:

ruby test.rb
# => this should be on the console
# => this should be back on the console
cat mytestfile.out
# => this goes in mytestfile
cat mytestfile1.out
# => this goes in mytestfile1

这是我通常将此功能打包为功能的方式:

Here's how I usually package this functionality into a function:

# Runs a block of code while blocking stdout.
# Note that /dev/null should be changed to NUL on Windows.
def silence_stdout(log = '/dev/null')
  old = $stdout.dup
  $stdout.reopen(File.new(log, 'w'))
  yield
  $stdout = old
end

用法:

silence_stdout 'mytestfile.out' do
  puts "this goes in mytestfile"
end

puts "this should be on the console"

silence_stdout 'mytestfile1.out' do
  puts "this goes in mytestfile1"
end

puts "this should be back on the console"

正如另一个提到的那样,仅在使用纯Ruby代码时才需要使用重新打开.上面的函数既可以用于纯Ruby代码,也可以用于例如写入STDOUT的C扩展.

as another poster mentioned, using reopen is only necessary when working with pure Ruby code. The function above works both with pure Ruby code and when using, for example, C extensions that write to STDOUT.

这篇关于将全局$ stdout重新分配给控制台-ruby的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆