2011-10-05 104 views
10

在计算过程中是否可以暂停Mathematica内核?这是一个例子。如何让Mathematica内核暂停以创建外部文件

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

我可以拿出上在指定的目录是否创建或不签入文件保持一个Do[..]循环解决方案。一旦找到文件,它将读取Mathematica代码的内容和其余部分处理数据。

有没有什么优雅的方法可以解决这个问题?

BR

+0

你在使用什么操作系统? –

+0

@ belisarius Windows 7,但希望它可以在Linux或Mac上完成.. – PlatoManiac

回答

12

尝试Pause[n],暂停至少n秒。

编辑:要使其工作的时间不确定,您需要反复轮询文件系统。 FileExistsQ做到这一点,你会使用它像

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

这将在最有浪费一个时间秒的时间等待。

更多编辑:您还可以将文件存在轮询放在批处理文件中,从而释放您的Mathematica会话。例如。编写一个批处理文件,名为C:含\ TEMP \ TEST.BAT:

@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 

而且从数学称它为:Run["start /min c:\\temp\\test.bat"]

这批演示假设apame_win64将写出文件alldone.txt完成。

+0

我不知道多少时间停止..它可变。 – PlatoManiac

+7

尝试:'while [!FileExistsQ [“filename”],Pause [1]]'这会在等待时浪费最多一秒。 – rcollyer

+1

@Chris,我将我的代码添加到了您的答案中,因为我认为我的评论获得的投票超过了您的答案,这有点不公平。 – rcollyer

6

你调用一个外部程序,程序是否会在文件创建完成后退出?如果是这样,那么RunThrough就是你要找的东西,请看RunThrough example。在那里,他们使用另一个Mathematica实例作为外部程序(如执行Mathematica脚本并等待其结果)。

如果外部程序在创建文件后必须保持运行,那么您可以使用单独的脚本(shell脚本,python,ruby ...)来检查文件是否存在。