我试图将 $stdout 设置为临时写入文件,然后再写入文件。
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 没有重置为控制台?
这个问题可以通过调用来解决dup http://ruby-doc.org/core-1.9.3/Object.html#method-i-dup on $stdout
更改之前:
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"
Output:
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
以下是我通常将此功能打包到函数中的方式:
# 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
Usage:
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 扩展等。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)