Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get continuous output from system calls in Ruby?

When you use a system call in a Ruby script, you can get the output of that command like this:

output = `ls`
puts output

That's what this question was about.

But is there a way to show the continuous output of a system call? For example, if you run this secure copy command, to get a file from a server over SSH:

scp user@someserver:remoteFile /some/local/folder/

... it shows continuous output with the progress of the download. But this:

output = `scp user@someserver:remoteFile /some/local/folder/`
puts output

... doesn't capture that output.

How can I show the ongoing progress of the download from inside my Ruby script?

like image 825
Nathan Long Avatar asked Mar 04 '11 13:03

Nathan Long


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 system in Ruby?

The Ruby system method is the simplest way to run an external command. It looks like this: system("ls") Notice that system will print the command output as it happens. Also system will make your Ruby program wait until the command is done.

How do I run a command line in Ruby?

Press Ctrl twice to invoke the Run Anything popup and execute the ruby script. rb command. In this case, you can specify the required command-line options and script arguments right in the popup, for example, ruby -v script. rb .


2 Answers

Try:

IO.popen("scp -v user@server:remoteFile /local/folder/").each do |fd|
  puts(fd.readline)
end
like image 173
tokland Avatar answered Oct 02 '22 00:10

tokland


I think you would have better luck using the ruby standard library to handle SCP (as opposed to forking a shell process). The Net::SCP library (as well as the entire Net::* libraries) are full featured and used with Capistrano to handle remote commands.

Checkout http://net-ssh.rubyforge.org/ for a rundown of what is available.

like image 21
Adam Avatar answered Oct 01 '22 23:10

Adam