8
$\begingroup$

Is there a reliable way to detect if the current code is running within a script?

Note that there are multiple ways to run a script, such as

wolframscript -file file.m
wolframscript -script file.m
math -script file.m

One might add math < file.m, but I do not need to handle this case.

"What have you tried?"

  • $BatchInput is True if piping a file to the kernel as in math < file.m, but not when using the math -script file.m.

  • $ScriptCommandLine is usually (always?) different from {} when using wolframscript (either with -script or -file), but not when using math -script.

  • $EvaluationEnvironment is "Script" with wolframscript 0file, but it is "Session" with math -script and wolframscript -script.

Best effort so far:

$inScript := $BatchInput || ($EvaluationEnvironment === "Script") || MemberQ[$CommandLine, "-script"]
$\endgroup$
4
  • $\begingroup$ How about using $FrontEnd. In the tests I did, it is Null when evaluated in a script. $\endgroup$ Nov 7, 2018 at 2:36
  • $\begingroup$ @RohitNamjoshi I am not looking to check if there is a front end present, but whether we're running interactive or in a script. Mathematica can be run interactively in command line mode, without a front end. It can also have an invisible front end attached when running in a script, but using UsingFrontEnd for some reason. $\endgroup$
    – Szabolcs
    Nov 7, 2018 at 8:39
  • $\begingroup$ Ah, I misunderstood your question. Thanks for clarifying. $\endgroup$ Nov 7, 2018 at 15:38
  • 1
    $\begingroup$ @RohitNamjoshi BTW if you want to check for the availability of a notebook interface, you can use $Notebooks (which is True|False) $\endgroup$
    – Szabolcs
    Nov 7, 2018 at 15:49

0

Your Answer

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

Browse other questions tagged or ask your own question.