2010-07-14 26 views
6

Quando uso IO::popen con un comando inesistente, ottengo un messaggio di errore stampata allo schermo:"command not found" salvataggio per IO :: popen

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

C'è un modo per catturare questo errore, quindi posso esaminare dal mio script?

risposta

2

Sì: aggiornamento a Ruby 1.9. Se lo esegui in 1.9, verrà invece generato uno Errno::ENOENT e sarai in grado di effettuare lo rescue.

(Edit) Ecco un modo hacker di farlo 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 
Problemi correlati