Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a command from Ruby displaying and capturing the output

Tags:

ruby

Is there some way to run a (shell) command from Ruby displaying but also capturing the output? Maybe with the help of some gem?

What I mean by displaying is not printing it at the end, but as it appears, so the user gets the feedback of what's going on when running slow commands.

like image 795
pupeno Avatar asked Apr 19 '12 08:04

pupeno


People also ask

How do I get output in Ruby?

Ruby has another three methods for printing output. In the example, we present the p , printf and putc methods. The p calls the inspect method upon the object being printed. The method is useful for debugging.

What is Ruby command?

Ruby command is a free and open source programming language; it is flexible and is feature rich. As the name suggests, ruby indeed is a jewel language which comes at a very low entry cost. Its plug and play capability and also easily readable syntax makes it very user-friendly.


2 Answers

You can run system call like this:

`sleep --help` 

Or like this

system "sleep --help" 

Or

%x{ sleep --help } 

In case of system it will print output and return true or nil, other two methods will return output

PS Oh. It is about displaying in real time.

So. You could use something like this:

system("ruby", "-e 100.times{|i| p i; sleep 1}", out: $stdout, err: :out) 

To print data in realtime and store it in variable:

output = [] r, io = IO.pipe fork do   system("ruby", "-e 3.times{|i| p i; sleep 1}", out: io, err: :out) end io.close r.each_line{|l| puts l; output << l.chomp} #=> 0 #=> 1 #=> 2 p output #=> ['0', '1', '2'] 

Or use popen

output = [] IO.popen("ruby -e '3.times{|i| p i; sleep 1}'").each do |line|   p line.chomp   output << line.chomp end #=> '0' #=> '1' #=> '2' p output #=> ['0', '1', '2'] 
like image 148
fl00r Avatar answered Sep 21 '22 14:09

fl00r


You can redirect the output

system 'uptime > results.log' 

or save the results.

result = `uptime` result = %x[uptime] 

see here. Getting progress information or output in realtime is more complicated, I doubt that there is a simple solution. Maybe it is possible with advanced process management functions such as Open3.popen3. You could also try to use a pseudo terminal with pty and grap the output there.

like image 34
0x4a6f4672 Avatar answered Sep 21 '22 14:09

0x4a6f4672