Chr*_*nen 5 wolfram-mathematica mathematica-frontend
此示例例程在内核窗口中生成两个Throw :: nocatch警告消息.它们可以以某种方式处理吗?
该示例包含在C:\ Temp中创建的文件"test.m"中的代码:
Needs["JLink`"];
$FrontEndLaunchCommand = "Mathematica.exe";
UseFrontEnd[NotebookWrite[CreateDocument[], "Testing"]];
Run Code Online (Sandbox Code Playgroud)
然后在Windows命令提示符下粘贴并运行这些命令:
PATH = C:\Program Files\Wolfram Research\Mathematica\8.0\;%PATH%
start MathKernel -noprompt -initfile "C:\Temp\test.m"
Run Code Online (Sandbox Code Playgroud)
附录
使用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[];
Run Code Online (Sandbox Code Playgroud)
和一个包含以下单个单元格的笔记本C:\ Temp\run.nb:
x1 = 0; While[x1 < 1000000,
If[Mod[x1, 100000] == 0,
Print["x1=" <> ToString[x1]]]; x1++];
NotebookSave[EvaluationNotebook[]];
NotebookClose[EvaluationNotebook[]];
Run Code Online (Sandbox Code Playgroud)
此代码从Windows命令提示符启动,将以交互方式运行并保存其输出.使用UsingFrontEnd或MathKernel -script"C:\ Temp\test.m"无法实现.
在初始化期间,内核代码处于防止中止的模式.
Throw/Catch是使用Abort实现的,因此它们在初始化期间不起作用.
一个显示问题的简单示例是将它放在test.m文件中:
Catch[Throw[test]];
Run Code Online (Sandbox Code Playgroud)
类似地,TimeConstrained,MemoryConstrained,Break,Trace系列,Abort和依赖它的函数(如某些数据paclet)在初始化期间会出现类似的问题.
您的问题的可能解决方案可能是考虑-script选项:
math.exe -script test.m
Run Code Online (Sandbox Code Playgroud)
另请注意,在版本8中有一个名为UsingFrontEnd的文档化函数,它执行UseFrontEnd所做的操作,但是是自动配置的,因此:
Needs["JLink`"];
UsingFrontEnd[NotebookWrite[CreateDocument[], "Testing"]];
Run Code Online (Sandbox Code Playgroud)
应该是test.m文件中所需的全部内容.
另请参见:Mathematica脚本
附录
使用-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];
]
Run Code Online (Sandbox Code Playgroud)
我希望这对你有用.它可以使用一些更多的改进,例如将笔记本的内核重置为原始内容并在保存后关闭笔记本,但此代码应该适用于此特定用途.
另外,我尝试了另一种方法,使用它:
UsingFrontEnd[ NotebookEvaluate[ "c:\\users\\arnoudb\\run.nb", InsertResults->True ] ]
Run Code Online (Sandbox Code Playgroud)
但是这会将内核终端会话踢进对话模式,这对我来说似乎是一个错误(如果这是一个有效的问题,我会检查并报告此情况).
归档时间: |
|
查看次数: |
896 次 |
最近记录: |