2010-07-14 62 views
6

當我使用IO::popen一個不存在的命令「未找到命令」,我得到打印到屏幕上的錯誤信息:拯救了IO :: popen方法

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

有什麼辦法,我可以抓住這個錯誤,所以我可以從我的腳本中檢查?

回答

2

是:升級到紅寶石1.9。如果你在1.9版本中運行該版本,則會增加一個Errno::ENOENT,而你將可以使用rescue它。

(編輯)這裏是1.8做的hackish的方式:

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