How to execute Windows CLI commands in Ruby?

前端 未结 2 425
被撕碎了的回忆
被撕碎了的回忆 2020-12-17 00:45

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 qou

相关标签:
2条回答
  • 2020-12-17 01:31

    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
    
    0 讨论(0)
  • 2020-12-17 01:43
    `"C:\Documents and Settings\test.exe"`
    

    or

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

    or whatever in qoutes

    0 讨论(0)
提交回复
热议问题