开发者

Confirm existance of executable (script, bat, cmd, exe) via a ruby file

开发者 https://www.devze.com 2023-01-01 23:33 出处:网络
Using a ruby file (or any rake f开发者_JS百科acility) I need to find out if the user who executes my script is able to execute certain shell commands. In particular g++ etc. Hopefully system independe

Using a ruby file (or any rake f开发者_JS百科acility) I need to find out if the user who executes my script is able to execute certain shell commands. In particular g++ etc. Hopefully system independent so if there is some g++.bat, g++.exe or just g++ (etc) it should say yes nevertheless, as long as its on the path and executable on the users system.

Example: if the user has a no-extention executable version of the file and a .cmd version of the file it should say "yes" for the no extension version on a linux system and "yes" to the .cmd version on a windows system. Since the users shell can only execute that version of the file.

The purpose of this is to allow the script to be self-configuring (as much as possible).

Any suggestions on how I might go about doing this?


A quick and dirty way is to simply attempt to execute g++ via the system command and check the return code, for example:

def gpp_exists
  return system("g++ --version")
end

You'd have to do some trickery to avoid getting unwanted output on the console (e.g. redirecting stdout/stderr based on correct OS syntax), but it couldn't be too bad.


Well, File contains both exists? and executable?. ENV['PATH'] gets the directories executables are in (at least on *nix - can someone confirm for Windows?). Combine the two with a bit of magic and you should have a solution.

Edit:

irb(main):001:0> ENV['PATH'].split(':').collect {|d| Dir.entries d if Dir.exists? d}.flatten.include? 'adduser'
=> true
irb(main):002:0> ENV['PATH'].split(':').collect {|d| Dir.entries d if Dir.exists? d}.flatten.include? 'foo'
=> false


i've required something similar (is it executable in the path) and use the system command but check the error code of return. according to this its a standard result in unix (127 = file not found) stackoverflow standard unix return codes

    def checkinstalled(program)
      stdop=system(program)
      result=$?
      exit_code=result.exitstatus 
      return !exit_code.eql?(127)
    end

can't say for windows however

0

精彩评论

暂无评论...
验证码 换一张
取 消