This can be relatively easily done using extremely useful $FrontEnd
option "ClearEvaluationQueueOnKernelQuit"
introduced by Chris Degnen.
Usage
Print @ $SessionID
quitAndEvaluate[
Print @ $SessionID
]
25183094379509806957
25183094575602627552
quitAndEvaluate[]
will restart kernel without aby additional tasks. It may be useful if you want to check init.m or Autoload behaviour.
You can provide procedures delayed in symbol definition (not so obvious since definitions are cleared in a process:
ext := (Print[1]; Print[2]);
quitAndEvaluate[ext]
Code
SetAttributes[quitAndEvaluate, HoldAll];
quitAndEvaluate[proc_Symbol] := Unevaluated[quitAndEvaluate[proc]] /. OwnValues[proc];
quitAndEvaluate[after___] := With[{
currentSetting = CurrentValue[$FrontEnd, "ClearEvaluationQueueOnKernelQuit"]
},
Composition[
(SelectionMove[#, All, Notebook]; SelectionEvaluate[#]) &
,
CreateDocument[#, Visible -> False, WindowSize -> {Automatic, 100}] &
,
Cell[#, "Input"] & /@ # &
,
BoxData /@ # &
]@{
MakeBoxes[ CurrentValue[ $FrontEndSession, "ClearEvaluationQueueOnKernelQuit" ] = False; ]
,
MakeBoxes[ Quit[]; ]
,
MakeBoxes[ after; CurrentValue[ $FrontEndSession,
"ClearEvaluationQueueOnKernelQuit" ] = currentSetting;
NotebookClose[EvaluationNotebook[]]; $Line = 0;]
}
]
There is a funny thing with WindowSize
. Even though the notebook is invisible, you have to set explicitly any dummy value, otherwise it won't work. :)
Description
It basicaly creates a new invisible notebook with 3 cells and evaluates it.
The first cell sets our option to False
.
The second Quit[]s
the Kernel.
The third restores FrontEnd option. Evaluates your code and deletes that notebook.