"ruby中的哪个":检查程序在$ PATH中是否存在来自ruby的内容 [英] "which in ruby": Checking if program exists in $PATH from ruby
问题描述
我的脚本在很大程度上依赖于外部程序和脚本. 我需要确保我需要调用的程序存在. 手动地,我会在命令行中使用哪个"来检查.
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 为File类添加了"which"方法. h3>
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.
这篇关于"ruby中的哪个":检查程序在$ PATH中是否存在来自ruby的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!