Last active
December 13, 2015 20:48
-
-
Save mark-rushakoff/4972746 to your computer and use it in GitHub Desktop.
How to simultaneously print and capture the output of an external command in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
cmd = %q[echo '3...'; sleep 1; | |
echo '2...'; sleep 1; | |
echo '1...'; sleep 1; | |
echo 'Liftoff!'] | |
puts '------ beginning command ------' | |
output_log = [] | |
IO.popen(cmd).each do |line| | |
puts line | |
output_log << "[#{Time.now}] #{line}" | |
end.close # Without close, you won't be able to access $? | |
puts '------ done with command ------' | |
puts "The command's exit code was: #{$?.exitstatus}" | |
puts 'Here is the log:' | |
puts output_log.join('') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment