Execute external program in ruby and wait for its execution

前端 未结 3 1073
没有蜡笔的小新
没有蜡笔的小新 2021-02-20 10:53

How do I start an external program (like an excel sheet) from ruby and wait for its execution resp. termination before continuing.

I know I can start the excel sheet wit

3条回答
  •  失恋的感觉
    2021-02-20 11:42

    As already stated, dropping the "start" will cause the Ruby script to wait.

    system("notepad.exe")
    

    Another way to do it in Ruby is with backticks.

    `notepad.exe` # Same effect. Will also accept #{} variable insertion 
    

    However, you pointed out Excel as an example. If you bring up a regular Windows command prompt, you will notice that while start excel path\to\sheet will open Excel whereas just excel path\to\sheet will not. You will get an error about how "excel" is not a recognized internal or external command. The way to fix this is to either add the path to Excel into your Environment Variables or to include the path to Excel in your system() call.

    EXCEL = File.join("C:", "Program Files", 
        "Microsoft Office", "OFFICE11", "excel.exe")
    `"#{EXCEL}" "path\to\sheet"` 
    

    (Using the backticks here is just my preference. I prefer it since it enables the variable insertion.) This will bring up an instance of Excel and the Ruby script will wait for the application's termination.

提交回复
热议问题