This works on my Windows machine (not sure how well it translates to Mac and Linux yet):
Place this in a file called test.wls
:
checks = { $Notebooks, Length[$CommandLine]===1, MemberQ[$CommandLine,"-wlbanner"], MemberQ[$CommandLine,"-noicon"] };
Print @ Switch[
checks,
{True,False,False,True}, "Running in notebook interface",
{False,True,False,False}, "Running in wolfram.exe",
{False,False,True,False}, "Running in wolframscript.exe",
{False,False,False,False}, "Running in test.wls"
];
Then run this file in different modes. First as a script:
C:\Users\arnoudb.WRI>test.wls
Running in test.wls
Then using wolframscript.exe
:
C:\Users\arnoudb.WRI>wolframscript
Wolfram Language 11.3.0 Engine for Microsoft Windows (64-bit)
Copyright 1988-2018 Wolfram Research, Inc.
In[1]:= Get["test.wls"]
Running in wolframscript.exe
Then using wolfram.exe
:
C:\Users\arnoudb.WRI>"C:\Program Files\Wolfram Research\Mathematica\11.3\wolfram.exe"
Mathematica 11.3.0 Kernel for Microsoft Windows (64-bit)
Copyright 1988-2018 Wolfram Research, Inc.
In[1]:= Get["test.wls"]
Running in wolfram.exe
And finally from a notebook interface:
Get["C:\\Users\\arnoudb.WRI\\test.wls"]
Running in notebook interface
Probably needs some work to get this more solid.
$ScriptCommandLine
is{}
$\endgroup$$ScriptCommandLine == {}
is the same as$Notebooks
, as far as I can tell. It tells me if I'm running code from a front end (vs. a command line), not whether I'm running code directly from a notebook/script (vs. importing it). I added some clarification to the question. $\endgroup$Initialization Cell
$\endgroup$main[]
function only evaluate if a certain global flag is set. When the file is read, ifGlobal`$EvaluateFlag
is notTrue
, you don't run themain[]
function. $\endgroup$