Execute external program in ruby and wait for its execution

前端 未结 3 1074
没有蜡笔的小新
没有蜡笔的小新 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:33

    Do not use start! The command system will wait for the result. In Windows prompt the start command starts programs asynchronously.

    system 'excel yout/path/sheet'
    

    Or you can use %x too, if you want an array as result :

    %x{ ls }
    

    If you have the start command in your command, %x will wait for the output anyway..

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-20 11:49

    The problem you are having is not with Ruby but the start command, this launches another program and returns immediately. You need to make that command wait for excel to finish using the wait flag:

    system('start /wait excel "my/path/to/the/sheet"')
    
    0 讨论(0)
提交回复
热议问题