【问题标题】:trying to check if command exists with ruby popen3尝试使用 ruby​​ popen3 检查命令是否存在
【发布时间】:2013-10-17 11:48:51
【问题描述】:

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

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)

为什么以及如何解决它?

【问题讨论】:

    标签: ruby stderr popen3


    【解决方案1】:

    似乎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"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-30
      • 2015-04-07
      • 2018-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-25
      • 2016-04-15
      相关资源
      最近更新 更多