7
$\begingroup$

I have a notebook that I also execute as a m file on the command line. Depending on whether I run the notebook or the m file, I want to use slightly different commands. For example, NotebookDirectory[] in the nb file should be replaced by Directory[] in the m file. Is there a way to read out how Mathematica was started (on the command line or as a notebook) so that I can use the same file to handle the two different situations?

Other solutions are welcome.

$\endgroup$
6
$\begingroup$

This question is more complicated that you might expect.

Things you can check:

  • Given how you want to use this, the simplest thing may be to just check if NotebookDirectory[] is different from $Failed.

  • The documentation would suggest $Notebooks, but be careful: this is True even if running in command line mode but connecting to a front end anyway, e.g. UsingFrontEnd[$Notebooks] will be True. For practical purposes it may work well.

  • There is $ParentLink. It is set to something else than Null when the kernel is being used through a MathLink connection, which includes the cases when there is a front end present, but may also include other scenarios when the kernel is used through MathLink. I checked that with MathematicaScript, $ParentLink is still Null (even though AFAIK MathematicaScript uses MathLink to invoke the kernel (??)).

  • There is $ScriptCommandLine, which will be non-empty when using MathematicaScript (but not when invoking the kernel from the command line in other ways).

  • There is $BatchInput (look it up).

  • $InputFileName will be set when reading an .m file using Get. This may be the most robust solution.

$\endgroup$
  • 2
    $\begingroup$ To check that $ParentLink is the usual FE, one can use MathLink`NotebookFrontEndLinkQ[$ParentLink] $\endgroup$ – Oleksandr R. May 9 '16 at 15:41

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.