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


all the cells get evaluated.

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

Feel free to add improvements or submit an alternative solution.

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

| improve this answer | |
  • $\begingroup$ Can you give an example of what you achieve with the above code? $\endgroup$ – Tugrul Temel Dec 6 '19 at 22:37

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.