Running a Command from Ruby Displaying and Capturing the Output

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

Is it possible to capture output from a system command and redirect it?

Using abort and an exit message, will pass the message to STDERR (and the script will fail with exit code 1). You can pass this shell command output in this way.

This is possibly not the only (or best) way, but it has worked for me in the past.

[edit]

You can also redirect the output to a file (using standard methods), and read that file outside the ruby 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

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} )

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

Log all output from a shell command

You can use IO::popen for this:

IO.popen("apt-get install foobar") do |apt|
apt.each do |line|
puts line
end
end

Hope this helps



Related Topics



Leave a reply



Submit