Running Mathematica notebooks in batch mode

Bookmark and Share

If you’re like me, you’re used to thinking of Mathematica as an interactive calculator, where you type in an expression and Mathematica evaluates it and spits out the result. But the Mathematica system actually incorporates a whole programming language, and as you might expect of any programming language, it’s possible to write Mathematica programs (scripts) that run non-interactively.

In order to write a Mathematica script, you create a text file which contains the expressions you want to evaluate (in normal programming terminology, the statements to execute). The conventional file extension for Mathematica scripts is .m. Each expression that you would normally type into the Mathematica window, you type into the script file, one per line. (Line breaks are allowed within expressions under certain circumstances.) You can then run the script using

math -script filename.m

(on Linux). The evaluated expressions, which Mathematica would normally show you right below where you typed in the input, are printed to standard output, so I recommend ending lines with a semicolon (which suppresses the output) by default. Only leave the semicolon off for the results you actually care about.

Keep in mind that a Mathematica script file is not what you get when you click “File > Save” in Mathematica’s graphical interface. That gives you a notebook, typically saved with file extension .nb, which contains not only the expressions to evaluate but also the generated output and a lot of formatting information about both the input and output. You can actually open up a notebook (an .nb file) in a text editor and see all the extra metadata that it associates with the expressions you type. Unfortunately, there’s no easy, one-click way to convert a notebook to a script, but it is possible:

  1. First delete all the generated output using “Cell > Delete All Output”.
  2. Delete all the cell labels of the form In[1]. Probably the easiest way to do this is to close the Mathematica notebook (make sure to save it as a .nb notebook first) and then open it again.
  3. Now save the notebook as a text file: go to “File > Save As” and choose the type “Plain Text (*.txt)” to save your notebook as a plain text file.
  4. Rename the file to change its extension from .txt to .m.
  5. Open it up in a text editor and check that it looks like it should.

If you find yourself using Mathematica scripts a lot, it can be useful to organize frequently-used code into packages. In that case, I highly recommend reading (and following) the useful tips in the package design tutorial. (Hat tip to Ted Ersek’s tips and tricks page for pointing me there)