“which in ruby”: Checking if program exists in $PATH from ruby

后端 未结 16 1116
萌比男神i
萌比男神i 2020-12-07 12:15

my scripts rely heavily on external programs and scripts. I need to be sure that a program I need to call exists. Manually, I\'d check this using \'which\' in the commandlin

16条回答
  •  醉酒成梦
    2020-12-07 12:33

    Use MakeMakefile#find_executable0 with Logging Disabled

    There are a number of good answers already, but here's what I use:

    require 'mkmf'
    
    def set_mkmf_log(logfile=File::NULL)
      MakeMakefile::Logging.instance_variable_set(:@logfile, logfile)
    end
    
    # Return path to cmd as a String, or nil if not found.
    def which(cmd)
      old_mkmf_log = MakeMakefile::Logging.instance_variable_get(:@logfile)
      set_mkmf_log(nil)
      path_to_cmd = find_executable0(cmd)
      set_mkmf_log(old_mkmf_log)
      path_to_cmd
    end
    

    This uses the undocumented #find_executable0 method invoked by MakeMakefile#find_executable to return the path without cluttering standard output. The #which method also temporarily redirects the mkmf logfile to /dev/null to prevent cluttering the current working directory with "mkmf.log" or similar.

提交回复
热议问题