tags:

views:

23

answers:

1

When I use IO::popen with a non-existent command, I get an error message printed to the screen:

 irb> IO.popen "fakefake"
  #=> #<IO:0x187dec>
 irb> (irb):1: command not found: fakefake

Is there any way I can capture this error, so I can examine from within my script?

+1  A: 

Yes: Upgrade to ruby 1.9. If you run that in 1.9, an Errno::ENOENT will be raised instead, and you will be able to rescue it.

(Edit) Here is a hackish way of doing it in 1.8:

error = IO.pipe
$stderr.reopen error[1]
pipe = IO.popen 'qwe' # <- not a real command
$stderr.reopen IO.new(2)
error[1].close

if !select([error[0]], nil, nil, 0.1)
  # The command was found. Use `pipe' here.
  puts 'found'
else
  # The command could not be found.
  puts 'not found'
end
Adrian