Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute external program in ruby and wait for its execution

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 with

system 'start excel "my/path/to/the/sheet"' 

but using this will only start the sheet and then continues.

like image 646
Sebastian Müller Avatar asked Jul 11 '11 11:07

Sebastian Müller


3 Answers

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..

like image 174
kisp Avatar answered Sep 23 '22 06:09

kisp


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"')
like image 24
Jonathan Avatar answered Sep 23 '22 06:09

Jonathan


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.

like image 40
Charles Caldwell Avatar answered Sep 21 '22 06:09

Charles Caldwell