13
$\begingroup$

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:

$\endgroup$

2 Answers 2

16
$\begingroup$

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.

$\endgroup$
5
  • $\begingroup$ I did not know NoteBookEvaluate and you are right: that's much sleeker than my solution. Thanks! $\endgroup$ Commented May 30, 2013 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$ Commented May 30, 2013 at 11:11
  • $\begingroup$ @Jacob +1. Are you sure NotebookEvaluate does not use the FrontEnd in background? $\endgroup$ Commented May 30, 2013 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$ Commented May 30, 2013 at 13:43
  • $\begingroup$ @AlexeyPopkov ah, it does use the front end! Sorry for the misdirection, I will edit. $\endgroup$ Commented May 30, 2013 at 13:46
8
$\begingroup$

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!

$\endgroup$
1
  • $\begingroup$ Can you give an example of what you achieve with the above code? $\endgroup$ Commented Dec 6, 2019 at 22:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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