How to execute Windows CLI commands in Ruby?

15,425

Solution 1

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

or

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

or whatever in qoutes

Solution 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
Share:
15,425
Apoorv Saxena
Author by

Apoorv Saxena

Updated on June 15, 2022

Comments

  • Apoorv Saxena
    Apoorv Saxena almost 2 years

    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.

  • fl00r
    fl00r about 13 years
    main idea is to wrap the path into quotes. I am not familiar with Windows so there can be any other restrictions.
  • Apoorv Saxena
    Apoorv Saxena about 13 years
    Don't know if the file I am working with has some constraints to work in a Ruby program or the way I am specifying the path of the file is incorrect but the thing is not working for me... But the method that you have told is correct!!!
  • stack1
    stack1 almost 9 years
    undefined method `capture3' for Open3:Module (NoMethodError) with ruby 1.8.7