拯救IO::popen出现的“command not found”错误

6
当我使用IO::popen来执行一个不存在的命令时,屏幕上会打印出一个错误信息:
 irb> IO.popen "fakefake"
  #=> #<IO:0x187dec>
 irb> (irb):1: command not found: fakefake

有没有办法捕获这个错误,以便我可以在我的脚本中进行检查?
1个回答

2

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接