由JLink或UseFrontEnd生成的Uncaught Throw

时间:2011-10-02 13:03:53

标签: wolfram-mathematica mathematica-frontend

此示例例程在内核窗口中生成两个Throw :: nocatch警告消息。他们能以某种方式处理吗?

该示例包含在C:\ Temp:

中创建的文件“test.m”中的代码
Needs["JLink`"];
$FrontEndLaunchCommand = "Mathematica.exe";
UseFrontEnd[NotebookWrite[CreateDocument[], "Testing"]];

然后在Windows命令提示符下粘贴并运行这些命令:

PATH = C:\Program Files\Wolfram Research\Mathematica\8.0\;%PATH%
start MathKernel -noprompt -initfile "C:\Temp\test.m"

enter image description here

附录

使用UseFrontEnd而不是UsingFrontEnd的原因是可能需要交互式前端来保留通常以交互方式运行的笔记本的输出和消息。例如,C:\ Temp \ test.m修改如下:

Needs["JLink`"];
$FrontEndLaunchCommand="Mathematica.exe";
UseFrontEnd[
nb = NotebookOpen["C:\\Temp\\run.nb"];
SelectionMove[nb, Next, Cell];
SelectionEvaluate[nb];
];
Pause[10];
CloseFrontEnd[];

和使用包含以下内容的单个单元格创建的笔记本C:\ Temp \ run.nb

x1 = 0; While[x1 < 1000000,
 If[Mod[x1, 100000] == 0,
  Print["x1=" <> ToString[x1]]]; x1++];
NotebookSave[EvaluationNotebook[]];
NotebookClose[EvaluationNotebook[]];

从Windows命令提示符启动的此代码将以交互方式运行并保存其输出。使用UsingFrontEnd或MathKernel -script“C:\ Temp \ test.m”无法实现这一点。

1 个答案:

答案 0 :(得分:5)

在初始化期间,内核代码处于防止中止的模式。

Throw / Catch是使用Abort实现的,因此它们在初始化期间不起作用。

显示问题的一个简单示例是将它放在test.m文件中:

Catch[Throw[test]];

类似地,像TimeConstrained,MemoryConstrained,Break,Trace系列,Abort和依赖它的那些函数(如某些数据paclet)在初始化期间会出现这样的问题。

问题的可能解决方案可能是考虑-script选项:

math.exe -script test.m

另外,请注意,在版本8中有一个名为UsingFrontEnd的文档化函数,它执行UseFrontEnd所做的操作,但是已自动配置,因此:

Needs["JLink`"];
UsingFrontEnd[NotebookWrite[CreateDocument[], "Testing"]];

应该是test.m文件中的所有内容。

另请参阅:Mathematica Scripts

<强>附录

使用-script和UsingFrontEnd的一种可能解决方案是使用'run.m脚本 包括在下面。这确实需要在内核配置选项中设置“测试”内核(基本上是“本地”内核设置的克隆)。

该脚本包括两个实用程序函数,NotebookEvaluatingQ和NotebookPauseForEvaluation,它们帮助脚本在保存之前等待客户端笔记本完成评估。这种方法的好处是所有评估控制代码都在'run.m'脚本中,因此客户端笔记本不需要在最后有一个NotebookSave [EvaluationNotebook []]语句。

NotebookPauseForEvaluation[nb_] := Module[{},While[NotebookEvaluatingQ[nb],Pause[.25]]]

NotebookEvaluatingQ[nb_]:=Module[{},
SelectionMove[nb,All,Notebook];
Or@@Map["Evaluating"/.#&,Developer`CellInformation[nb]]
]

UsingFrontEnd[
nb = NotebookOpen["c:\\users\\arnoudb\\run.nb"];
SetOptions[nb,Evaluator->"Test"];
SelectionMove[nb,All,Notebook];
SelectionEvaluate[nb];
NotebookPauseForEvaluation[nb];
NotebookSave[nb];
]

我希望这对你有用。它可以使用一些更多的改进,例如将笔记本电脑的内核重置为原始内容并在保存后关闭笔记本电脑, 但是这段代码应该适用于这个特定目的。

另一方面,我尝试了另一种方法,使用它:

UsingFrontEnd[ NotebookEvaluate[ "c:\\users\\arnoudb\\run.nb", InsertResults->True ] ]

但这会将内核终端会话踢进对话模式,这似乎是一个错误 对我来说(如果这是一个有效的问题,我会检查并报告此事。)