How do I temporarily redirect stderr in Ruby?
In Ruby, $stderr
refers to the output stream that is currently used as stderr, whereas STDERR
is the default stderr stream. It is easy to temporarily assign a different output stream to $stderr
.
require "stringio"
def capture_stderr
# The output stream must be an IO-like object. In this case we capture it in
# an in-memory IO object so we can return the string value. You can assign any
# IO object here.
previous_stderr, $stderr = $stderr, StringIO.new
yield
$stderr.string
ensure
# Restore the previous value of stderr (typically equal to STDERR).
$stderr = previous_stderr
end
Now you can do the following:
captured_output = capture_stderr do
# Does not output anything directly.
$stderr.puts "test"
end
captured_output
#=> "test\n"
The same principle also works for $stdout
and STDOUT
.
How to redirect STDOUT and STDERR in Ruby and make them equal?
2.1.3 :005 > %x{(ls -d /boot 2>&1) | tee /dev/stderr}
/boot
=> "/boot\n"
2.1.3 :006 > %x{(ls /no_such_file 2>&1) | tee /dev/stderr}
ls: cannot access /no_such_file: No such file or directory
=> "ls: cannot access /no_such_file: No such file or directory\n"
Redirect stdout and stderr in real time
STDOUT.sync = true
if you don't want to flush
every time
How can I log STDOUT and STDERR to a single file and show only STDERR in the console using Ruby?
This Ruby script satisfies my needs, but maybe there is a better way.
logPath = ARGV[0]
logFolder = File.dirname(logPath)
command = ARGV.slice(1..-1).join(" ")
`mkdir -p #{logFolder}`
exec "#{command} 2>&1 >> #{logPath} | tee -a #{logPath}"
Redirect stderr and stdout in Bash
Take a look here. It should be:
yourcommand &> filename
It redirects both standard output and standard error to file filename.
How do I redirect an STDOUT to a Ruby program using pipes?
Use gets to receive the input from STDOUT via pipes.
Create a file cowspeak.rb:
puts "Cow speaks: " + gets
Demo:
❯ echo "hey there" | ruby cowspeak.rb
Cow speaks: hey there
Related Topics
What Is the Use of Gemfile in Rails
Ruby Regular Expression to Match a Url
Nokogiri Gem Installation Error
Match a String Against Multiple Patterns
How to Format the Value Shown in a Rails Edit Field
How to Match Something With Regex That Is Not Between Two Special Characters
How to Use CSS with a Ruby on Rails Application
Rails: Specified 'Mysql2' for Database Adapter But the Gem Is Not Loaded
Find the Newest Record in Rails 3
How to Search a Folder and All of Its Subfolders For Files of a Certain Type
Counter_Cache With Has_Many :Through
Rails Model, View, Controller, and Helper: What Goes Where