8

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"]
Szabolcs
  • 234,956
  • 30
  • 623
  • 1,263
  • How about using $FrontEnd. In the tests I did, it is Null when evaluated in a script. – Rohit Namjoshi Nov 07 '18 at 02:36
  • @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. – Szabolcs Nov 07 '18 at 08:39
  • Ah, I misunderstood your question. Thanks for clarifying. – Rohit Namjoshi Nov 07 '18 at 15:38
  • 1
    @RohitNamjoshi BTW if you want to check for the availability of a notebook interface, you can use $Notebooks (which is True|False) – Szabolcs Nov 07 '18 at 15:49

0 Answers0