What I do is the following.
Save the following code as a text file in a permanent location under the name MathematicaLauncher.scpt
:
tell application "System Events"
try
get process "Mathematica"
on error -- Not running, launch and run
launch application "Mathematica"
-- May need to wait until application finishes launching
repeat while "Mathematica" is not in name of processes
delay 0.5
end repeat
end try
end tell
tell application "Mathematica"
activate
do script "notebook0=NotebookOpen[\"~/MyFile.nb\"];Clear[notebook0];NotebookClose[EvaluationNotebook[]]"
end tell
On the last line before end tell
, replace the name and path of MyFile.nb
with the location of your actual Mathematica notebook, of course!
Now from the Terminal, just type
osascript MathematicaLauncher.scpt
and the notebook will open. If you want to do additional things after opening the notebook, add the corresponding notebook manipulation commands after NotebookOpen[\"~/MyFile.nb\"];
.
As an additional layer, you can now save the osascript
terminal command in a shell
script if needed - for example:
#!/bin/sh
osascript MathematicaLauncher.scpt
Save this in the same directory as the scpt
file and make it executable, and you're done.
Explanation
The launcher is written in AppleScript
, and the reason I do this is so that I have more flexibility of doing other things in addition to launching the notebook. What the script does is to create a temporary notebook0
from which the target notebook MyFile.nb
is opened. After opening it, you can for example add additional lines to MyFile.nb
before evaluating it. That can be done using SelectionMove
and NotebookWrite
.
In particular, you just wanted to evaluate your notebook. In that case you'd put your command NotebookEvaluate[\"~/MyFile.nb\"];
in the string following do script
.
More info
As mentioned in the comments, you have to first start Mathematica normally by clicking on the Application, and disable the splash screen that appears at startup by default. It blocks execution of the script that AppleScript
is trying to send it. That screen is the first thing I disable whenever I get a new version of Mathematica, so I almost forgot it exists.
Other than that, I've been using this method to launch and manipulate notebooks almost every day without problems, across updates to both Mathematica and OS X.
I actually prefer to save the AppleScript
not as a shell script but as an Application using AppleScript Editor
, because then I can put its icon in the dock and launch the process with a mouse click. So instead of saving the script at the top in a text file, you could paste it into AppleScript Editor
and go from there.
UsingFrontEnd
approach. When I tried your example, I get a Terminal message saying thatCFURLCreateWithString
was passed an invalid string. $\endgroup$