Capturing stderr from Kernel.exec

Hello,

I'm trying to run some simple commands using Kernel.exec but need to capture the stderr for them. Is there an (easy) way to do it with just ruby and the standard library or should I get open4?

Thanks,
-carl

open4 adds quite a bit to open3, which is in the stdlib. so depending on your
exact needs you may or may not need it.

however, by capture i assume you are on unix, since otherwise you cannot fork
and exec just replaces the calling process so theres nothing to capture. that
being the case you can just

   out_err = ''

   IO.popen("#{ cmd } 2>&1") do |pipe|
     while((line = pipe.gets))
       out_err << line
     end
   end

if you need to separate them you can do

   require 'open3'

   stdout, stderr = '', ''

   Open3.popen3(cmd) do |i,o,e|
     i.close

     while((line = o.gets))
       stdout << line
     end

     while((line = e.gets))
       stderr << line
     end
   end

open4, as mentioned, does a whole lot more - check out the docs/samples.

regards.

-a

ยทยทยท

On Sat, 9 Sep 2006, Carl Lerche wrote:

Hello,

I'm trying to run some simple commands using Kernel.exec but need to capture
the stderr for them. Is there an (easy) way to do it with just ruby and the
standard library or should I get open4?

Thanks,
-carl

--
what science finds to be nonexistent, we must accept as nonexistent; but what
science merely does not find is a completely different matter... it is quite
clear that there are many, many mysterious things.
- h.h. the 14th dalai lama

Carl Lerche wrote:

Hello,

I'm trying to run some simple commands using Kernel.exec but need to
capture the stderr for them. Is there an (easy) way to do it with
just ruby and the standard library or should I get open4?

Thanks,
-carl

Kernel#exec never returns control; it replaces the ruby process with
the one you pass it. You need open3 (stdlib) or popen4.

[1] http://ruby-doc.org/stdlib/libdoc/open3/rdoc/index.html
[2] http://popen4.rubyforge.org/

Regards,
Jordan