# Evaluate Initialization Cells of another notebook

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:

-

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.

-
I did not know NoteBookEvaluate and you are right: that's much sleeker than my solution. Thanks! – Aart Goossens May 30 '13 at 11:07
@A.Goossens Well, I'm glad you asked :). With all the Notebook functions it can be hard to find the right one. – Jacob Akkerboom May 30 '13 at 11:11
@Jacob +1. Are you sure NotebookEvaluate does not use the FrontEnd in background? – Alexey Popkov May 30 '13 at 13:41
@AlexeyPopkov Ah yes, maybe there was a bit of bluff there. I will use it from shell interface to make sure – Jacob Akkerboom May 30 '13 at 13:43
@AlexeyPopkov ah, it does use the front end! Sorry for the misdirection, I will edit. – Jacob Akkerboom May 30 '13 at 13:46

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!

-