19
$\begingroup$

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.

Motivation

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

$\endgroup$
16
$\begingroup$

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.

$\endgroup$
  • 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.