Capturing stderr from Kernel.exec

C

Carl Lerche

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
 
M

MonkeeSage

A

ara.t.howard

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top