How to execute Windows CLI commands in Ruby?

2019-01-24 16:01发布

问题:

I have a file located in the directory "C:\Documents and Settings\test.exe" but when I write the command `C:\Documents and Settings\test.exe in single qoutes(which I am not able to display in this box), used for executing the commands in Ruby, I am not able to do so and the error that I recieve is No file or Directory found. I have tried replacing "\" with "//" and "\" but nothing seems to work. I have also used system, IO.popen and exec commands but all efforts are in vain. Also exec commands makes the program to make an exit which I don't want to happen.

Thanks in advance.

回答1:

`"C:\Documents and Settings\test.exe"`

or

`exec "C:\Documents and Settings\test.exe"`

or whatever in qoutes



回答2:

The backtick environment is like double-quotes, so backslash are used for escaping. Further, Ruby will interpret the spaces as separating command-line arguments, so you need to quote the entire thing:

`"C:\\Documents and Settings\\test.exe"`

Another option is to use system and force a second argument. If system gets more than one argument, it treats the first argument as the path to the command to execute and you don't need to quote the command:

system('C:\Documents and Settings\test.exe','')

Note the use of single quotes, so we don't have escape the backslashes.

Of course, this won't get you the standard out/error, so if you are on Ruby 1.9.2, you can use the awesomely handy Open3 library, which works like system, but gives you more information about the process you just ran:

require 'open3'

stdout,stderr,status = Open3.capture3('C:\Documents and Settings\test.exe','')

puts stdout # => string containing standard output of your command
puts stderr # => string containing standard ERROR of your command
if status.success?
  puts "It worked!"
else
  puts "OH NOES! Got exit code #{status.exitstatus}"
end