本文介绍了“which in ruby​​":从 ruby​​ 检查程序是否存在于 $PATH 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的脚本严重依赖外部程序和脚本.我需要确保我需要调用的程序存在.手动,我会在命令行中使用which"进行检查.

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 commandline.

对于 $PATH 中的东西,是否有等效于 File.exists? 的东西?

Is there an equivalent to File.exists? for things in $PATH?

(是的,我想我可以解析 %x[which scriptINeedToRun] 但这不是超级优雅.

(yes I guess I could parse %x[which scriptINeedToRun] but that's not super elegant.

谢谢!亚尼克

更新:这是我保留的解决方案:

UPDATE: Here's the solution I retained:

 def command?(command)
       system("which #{ command} > /dev/null 2>&1")
 end


更新 2:出现了一些新答案 - 至少其中一些提供了更好的解决方案.

更新 3:ptools gem 添加了一个which"File 类的方法.


UPDATE 2: A few new answers have come in - at least some of these offer better solutions.

Update 3: The ptools gem has adds a "which" method to the File class.

推荐答案

真正的跨平台解决方案,在 Windows 上正常工作:

True cross-platform solution, works properly on Windows:

# Cross-platform way of finding an executable in the $PATH.
#
#   which('ruby') #=> /usr/bin/ruby
def which(cmd)
  exts = ENV['PATHEXT'] ? ENV['PATHEXT'].split(';') : ['']
  ENV['PATH'].split(File::PATH_SEPARATOR).each do |path|
    exts.each do |ext|
      exe = File.join(path, "#{cmd}#{ext}")
      return exe if File.executable?(exe) && !File.directory?(exe)
    end
  end
  nil
end

这不使用主机操作系统嗅探,并尊重 $PATHEXT 列出 Windows 上可执行文件的有效文件扩展名.

This doesn't use host OS sniffing, and respects $PATHEXT which lists valid file extensions for executables on Windows.

脱壳到which 适用于许多系统但不是所有系统.

Shelling out to which works on many systems but not all.

这篇关于“which in ruby​​":从 ruby​​ 检查程序是否存在于 $PATH 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 15:32