13

Although there may be better ways to get data and definitions from another notebook (packages, read/write dumps, ...), sometimes it is convenient to just evaluate the initialization cells from another notebook to re-use the data and definitions.

Normally I would open this notebook and manually Evaluate Initialization Cells, but I was wondering if there is a way to do this automatically, i.e. with some code.

Question: is there a way to evaluate the Initialization Cells of a certain notebook by filename?

Related questions:

Aart Goossens
  • 1,638
  • 12
  • 21

2 Answers2

16

I think it is more convenient to use NotebookEvaluate. We can do

NotebookEvaluate[filename, EvaluationElements-> "InitializationCell"]

Confusing here may be that this has the same result as

NotebookEvaluate[filename, EvaluationElements -> Automatic]

Even though if we simply do

NotebookEvaluate[filename]

all the cells get evaluated.

Jacob Akkerboom
  • 12,215
  • 45
  • 79
8

I'm questioning AND answering this because I was looking for a feature like this for a while and now stumbled across FrontEndToken["EvaluateInitialization"] which does exactly what I wanted.

Here is the code to make it work:

filename = SystemDialogInput["FileOpen"];
nb = NotebookOpen[filename];
FrontEndExecute[FrontEndToken[nb, "EvaluateInitialization"]];
NotebookClose[nb]

Feel free to add improvements or submit an alternative solution.

Hope you like and use this feature as much as I do!

Aart Goossens
  • 1,638
  • 12
  • 21