Getting Output of System() Calls in Ruby

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

Return output from system command in Ruby?

You could use

output = `heroku create`

See: http://ruby-doc.org/core/classes/Kernel.html

How do I get the STDOUT of a ruby system() call while it is being run?

As in the linked question, the answer is again not to use system at all as system does not support this.

However this time the solution isn't to use backticks, but IO.popen, which returns an IO object that you can use to read the input as it is being generated.

Can I get continuous output from system calls in Ruby?

Try:

IO.popen("scp -v user@server:remoteFile /local/folder/").each do |fd|
puts(fd.readline)
end

Setting input for system() calls in ruby

Don't use system at all for this sort of thing, system is best for running an external command that you don't need to talk to.

Use Open3.open3 or Open3.open2 to open up some pipes to your external process then write to the stdin pipe just like writing to any other IO channel; if there is any output to deal with, then you can read it straight from the stdout pipe just like reading from any other input IO channel.

Getting the value of a system call

You can go with

d = `date`
e = IO.popen("date").read

Take some time also with IO.popen, IO.popen2, IO.popen3.

System call in Ruby

system("mv #{@SOURCE_DIR}/#{my_file} #{@DEST_DIR}/#{file})

can be replaced with

system("mv", "#{@SOURCE_DIR}/#{my_file}", "#{@DEST_DIR}/#{file}")

which reduces the chances of a command line injection attack.

Need to store output of `system`

If you need to extract only md5 hash from that output you can use this:

src_chksum = `CertUtil -hashfile "C:\Users\Public\Videos\Wildlife.wmv" MD5`  #make sure you use the backticks instead of single quotation marks

md5_hash = src_chksum.split("\n")[1].gsub(' ', '')

How to get the output of curl

Kernel#system Doesn't Capture Standard Output

Kernel#system only returns true, false or nil, so you can't capture command output that way. Instead, use Kernel#` (or its alternative %x{} syntax) to capture standard output. For example:

url    = 'https://ca.yahoo.com/'
output = %x(curl "#{url}")

For more complex things, you may also want to look at the Open3 module from the Ruby Standard Library. It has various methods for supporting pipelines, and different ways to treat standard input, standard output, and standard error separately when necessary.



Related Topics



Leave a reply



Submit