Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rescuing "command not found" for IO::popen

Tags:

ruby

popen

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?

like image 865
rampion Avatar asked Jul 14 '10 22:07

rampion


1 Answers

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
like image 159
Adrian Avatar answered Oct 19 '22 23:10

Adrian