From: dusty Date: 2007-11-28T08:20:00+09:00 Subject: Re: How to redirect a "system" standard output to a variable On Nov 27, 3:58 pm, Venks 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, 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 ---------- Running command: ls pid: 11208 stdout: test.rb stderr: exitcode 0 ----------