The question is how to quit the kernel, start a new session automatically, and to be able to run such procedure from e.g. Button.

This is especially useful when you can't count on Dynamic (80560) or you don't want to care if a given cell is currently visible.


when developing packages I'm often deleting all output, quitting kernel, loading the package. This can be done in two steps/shortcuts. I want one :)

There is closely related/duplicate, but "too old to migrate" question, without final anwer, in SO:

Quit Kernel in Mathematica...


This can be relatively easily done using extremely useful $FrontEnd option "ClearEvaluationQueueOnKernelQuit" introduced by Chris Degnen.


Print @ $SessionID

    Print @ $SessionID



  • 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]);


SetAttributes[quitAndEvaluate, HoldAll];

quitAndEvaluate[proc_Symbol] := Unevaluated[quitAndEvaluate[proc]] /. OwnValues[proc];

quitAndEvaluate[after___] := With[{
 currentSetting = CurrentValue[$FrontEnd, "ClearEvaluationQueueOnKernelQuit"]
    (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. :)


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.

| improve this answer | |
  • 1
    $\begingroup$ I think there should be a $Line=0; after NotebookClose[EvaluationNotebook[]]; $\endgroup$ – Rolf Mertig May 18 '15 at 22:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.