Running a shell command from Ruby: capturing the output while displaying the output?
runner.rb
STDOUT.print "Enter your password: "
password = gets.chomp
puts "Here is your password: #{password}"
Note STDOUT.print
start.rb
require "stringio"
buffer = StringIO.new
$stdout = buffer
require "runner"
$stdout = STDOUT
buffer.rewind
puts buffer.read.match(/Here is your (password: .*)/).captures[0].to_s
output
Enter your password: hello
password: hello
Read more...
I recently did a write-up on this here: Output Buffering with Ruby
Ruby: execute bash command, capture output AND dump to screen at the same time
Just tee the stdout stream to stderr like so:
ruby -e 'var = `ls | tee /dev/stderr`; puts "\nFROM RUBY\n\n"; puts var' | nl
ruby -e 'var = `ls | tee /dev/stderr`; puts "\nFROM RUBY\n\n"; puts var' 2>&1 | nl
Run Shell Script from Ruby File and Capture the Output
Don't use system
, it does not capture STDOUT. Use backticks (or %x()
):
output = %x( #{my_script} )
Getting output of system() calls in Ruby
I'd like to expand & clarify chaos's answer a bit.
If you surround your command with backticks, then you don't need to (explicitly) call system() at all. The backticks execute the command and return the output as a string. You can then assign the value to a variable like so:
output = `ls`
p output
or
printf output # escapes newline chars
Related Topics
How Does One Downgrade Jekyll to Work with Github Pages
Capturing Logger Output Inside a Method
Groups in a Gemfile in Rails 3
How to Send Message to All Client Except Sender in Rails/Actioncable
Rvm with Jruby 1.7.0 "Unknown Ruby Interpreter"
What's the Easiest Way to Send a Message Through Outlook with Ruby
How to Get a Hash Value by Numeric Index
How to Declare a Rake Task That Depends on a Parameterized Task
How to Connect to a Mongodb from Ruby Code
Download and Write .Tar.Gz Files Without Corruption
Using Rvm, But Can't Set Current Ruby Version (Ubuntu 11.10)
Truncate a Floating Point Number Without Rounding Up
Lion: Problem with Rvm Installing Rubies - Problem Related to Openssl
How Does Rake Db::Migrate Actually Work
Cancan Load_And_Authorize_Resource Triggers Forbidden Attributes