cod*_*ver 5 ruby iostream stdout
我试图设置$ 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"
Run Code Online (Sandbox Code Playgroud)
这是输出.
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
Run Code Online (Sandbox Code Playgroud)
我不确定为什么$ stdout没有重置到控制台?
在更改之前调用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"
Run Code Online (Sandbox Code Playgroud)
输出:
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
Run Code Online (Sandbox Code Playgroud)
以下是我通常将此功能打包到函数中的方法:
# 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
Run Code Online (Sandbox Code Playgroud)
用法:
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"
Run Code Online (Sandbox Code Playgroud)
编辑:正如另一张海报所提到的,只有在使用纯Ruby代码时才需要使用reopen.上面的函数既可以使用纯Ruby代码,也可以使用例如写入STDOUT的C扩展.