How do I redirect stderr and stdout to file for a Ruby script?

帅比萌擦擦* 提交于 2019-12-28 02:50:06

问题


How do I redirect stderr and stdout to file for a Ruby script?


回答1:


From within a Ruby script, you can redirect stdout and stderr with the IO#reopen method.

# a.rb
$stdout.reopen("out.txt", "w")
$stderr.reopen("err.txt", "w")

puts 'normal output'
warn 'something to stderr'
$ ls
a.rb
$ ruby a.rb
$ ls
a.rb    err.txt out.txt
$ cat err.txt 
something to stderr
$ cat out.txt 
normal output



回答2:


Note: reopening of the standard streams to /dev/null is a good old method of helping a process to become a daemon. For example:

# daemon.rb
$stdout.reopen("/dev/null", "w")
$stderr.reopen("/dev/null", "w")



回答3:


def silence_stdout
  $stdout = File.new( '/dev/null', 'w' )
  yield
ensure
  $stdout = STDOUT
end



回答4:


./yourscript.rb 2>&1 > log.txt

will redirect stdout and stderr to the same file.



来源:https://stackoverflow.com/questions/3018595/how-do-i-redirect-stderr-and-stdout-to-file-for-a-ruby-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!