How to redirect a "system" standard output to a variable

Hi,

I need to redirect any standard output thrown when using a system call into
a Ruby variable. I tried to search for a solution but couldn't find anything
that worked. May be I am not using the right search terms.

Here is what I am trying to do.

begin

  `rm somefile`

end

If "somefile" doesn't exist the OS throws the message "rm: cannot remove
`somefile': No such file or directory" which I want to capture into a
variable.

Thanks,

I use open4 for things like that. Try this it will show you how it
works.
http://codeforpeople.com/lib/ruby/open4/

# test.rb
require 'rubygems'
require 'open4'

commands = ["rm somefile","ls"]
commands.each do |command|
  status = Open4::popen4(command) do |pid,stdin,stdout,stderr|
    puts "Running command: #{command}\n\n"
    puts "pid:\n#{pid}"
    puts "\nstdout:\n#{stdout.read.strip}"
    puts "\nstderr:\n#{stderr.read.strip}"
  end
  puts "\nexitcode\n#{status.exitstatus}\n"
  puts "----------\n\n\n"
end

$ ruby test.rb
Running command: rm somefile

pid:
11207

stdout:

stderr:
rm: somefile: No such file or directory

exitcode
1

···

On Nov 27, 3:58 pm, Venks <venkatesh.man...@gmail.com> wrote:

Note: parts of this message were removed by the gateway to make it a legal Usenet post.

Hi,

I need to redirect any standard output thrown when using a system call into
a Ruby variable. I tried to search for a solution but couldn't find anything
that worked. May be I am not using the right search terms.

Here is what I am trying to do.

begin

  `rm somefile`

end

If "somefile" doesn't exist the OS throws the message "rm: cannot remove
`somefile': No such file or directory" which I want to capture into a
variable.

Thanks,

----------

Running command: ls

pid:
11208

stdout:
test.rb

stderr:

exitcode
0
----------

sys_msg = `rm /Users/Desktop/foo.txt 2>&1`
sys_msg # => "rm: /Users/Desktop/foo.txt: No such file or directory\n"

Regards, Morton

···

On Nov 27, 2007, at 3:58 PM, Venks wrote:

Hi,

I need to redirect any standard output thrown when using a system call into
a Ruby variable. I tried to search for a solution but couldn't find anything
that worked. May be I am not using the right search terms.

Here is what I am trying to do.

begin

  `rm somefile`

end

If "somefile" doesn't exist the OS throws the message "rm: cannot remove
`somefile': No such file or directory" which I want to capture into a
variable.

Thanks,