0

我正在尝试使用以下代码检查系统命令是否存在:

require 'open3'

Open3.popen3('non-existing command') do |stdin, stdout, stderr, thread|
  exit_error = stderr.readlines
  if exit_error["No such file or directory"]
    puts "command not found"
  end
end

但是它只是崩溃并显示以下错误消息并且不会继续:

/home/pavel/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/open3.rb:211:in `spawn': No such file or directory - non-existing (Errno::ENOENT)

为什么以及如何解决它?

4

1 回答 1

2

如果找不到命令,似乎会Open3.popen3引发异常;Errno::ENOENT所以你只需要从那个例外中解救出来:

require 'open3'

begin
  Open3.popen3('non-existing command') do |stdin, stdout, stderr, thread|
  end
rescue Errno::ENOENT
  puts "command not found"
end

#=> outputs "command not found"
于 2013-10-17T12:29:52.953 回答