How can we evaluate a Mathematica notebook from the command line (i.e. when running the kernel in command line mode)?
Suppose we're working on a remote machine. I know it is possible to convert the notebook to an m-file, and evaluate that, but I'm curious if it's possible to do this directly using the notebook.
This is what I have so far:
First, we need to start a headless X server on the remote Linux machine, so the front end can run there (and open the notebook). Skip this step if you're working on a local machine.
Xvfb :1 &
export DISPLAY=:1
After this I started a Mathematica kernel (math
) and did the following.
It's necessary to use UsingFrontEnd
because opening notebook requires a front end. test.nb has a single input cell containing a=1
.
In[1]:= nb=UsingFrontEnd@NotebookOpen["test.nb"]
Out[1]= -NotebookObject-
After trying to evaluate the notebook, apparently I get a dialog, and I need to use Return[]
to return. I am not sure why the input line starts counting from 1 again (a new kernel was started by the front end?) Note that a
didn't gain a value.
In[2]:= UsingFrontEnd@NotebookEvaluate[nb]
In[1]:= a
Out[1]= a
In[2]:= Return[]
Out[2]= a
After returning from the dialog, a
still doesn't have a value.
In[3]:= a
Out[3]= a