为IO :: popen抢救“未找到命令”

当我使用IO::popen和不存在的命令时,我会在屏幕上显示一条错误消息:

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

有什么方法可以捕获这个错误,所以我可以从我的脚本中检查?

是的:升级到ruby 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