如何将stderr和stdout重定向到Ruby脚本的文件中?

时间:2021-02-27 00:06:55

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

如何将stderr和stdout重定向到Ruby脚本的文件中?

4 个解决方案

#1


58  

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

在Ruby脚本中,可以使用IO# restart方法重定向stdout和stderr。

# 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


13  

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

注意:重新打开到/dev/null的标准流是帮助进程成为守护进程的一种很好的老方法。例如:

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

#3


7  

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

#4


5  

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

will redirect stdout and stderr to the same file.

将stdout和stderr重定向到同一个文件。

#1


58  

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

在Ruby脚本中,可以使用IO# restart方法重定向stdout和stderr。

# 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


13  

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

注意:重新打开到/dev/null的标准流是帮助进程成为守护进程的一种很好的老方法。例如:

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

#3


7  

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

#4


5  

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

will redirect stdout and stderr to the same file.

将stdout和stderr重定向到同一个文件。