Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make Mathematica kernel pause for an external file creation

Is it possible to pause Mathematica kernel during a computation? Here is an example.

Module[{},
       Mathematica code....
       ..........
       ..........
       {
        Calls an external program with some argument
        Needs to wait for an external program to create a file (* How ?*)
        }
       Mathematica code using that file content....
       ...........
       ...........
      ]

I can come up with a Do[..] loop solution that keeps on checking in a specified directory whether a file is created or not. Once it finds the file it reads the content and rest of the Mathematica code processes the data.

Is there any elegant way to solve this problem?

BR

like image 602
PlatoManiac Avatar asked Oct 05 '11 17:10

PlatoManiac


2 Answers

Try Pause[n], pauses for at least n seconds.

Edit: to make it work for an indeterminate amount of time, you need to repeatedly poll the filesystem. FileExistsQ does this, and you'd use it like

While[!FileExistsQ[ "filename" ], Pause[1]]

which would at most have one second of wasted time while waiting.

Further Edit: You can also put the file existence poll in a batch file thereby freeing up your Mathematica session. E.g. make a batch file called C:\Temp\Test.bat containing:

@echo off
start /min apame_win64 input
echo Loop commenced %TIME%
:loop
rem wait three seconds
ping localhost -n 3 > nul
if not exist c:\temp\alldone.txt goto loop
rem wait while file is completely written out
ping localhost -n 3 > nul
rem then terminate the process
taskkill /f /fi "imagename eq apame_win64.exe"
exit

And call it from Mathematica: Run["start /min c:\\temp\\test.bat"]

This batch demo assumes apame_win64 will write out a file alldone.txt to complete.

like image 80
Chris Degnen Avatar answered Sep 20 '22 13:09

Chris Degnen


You call an external program, does that program exit once the file is created? If so, then RunThrough is what you're looking for, see the RunThrough example. There they use another instance of Mathematica as the external program (like executing a Mathematica script and waiting for its result).

If the external program has to remain running after the file was created then you can use a separate script (shell script, python, ruby...) to check if the file exists.

like image 44
Matthias Berth Avatar answered Sep 17 '22 13:09

Matthias Berth