A common convention in python is to structure the main functionality of a script as follows, so it can be both run as a script directly or imported without executing main()
at the time of import:
def main():
do_stuff()
if __name__ == '__main__':
main()
Is there a similar variable that gets set in Julia, so that the script can be aware of whether it was imported using require("script.jl"
) or executed directly?
For example, say I have two scripts, a.jl
and b.jl
, along with a magic_function()
that behaves as follows:
a.jl:
println("Did we execute a.jl directly? ", magic_function())
b.jl:
require("a.jl")
Executing the following commands results in ...
> julia a.jl
Did we execute a.jl directly? true
> julia b.jl
Did we execute a.jl directly? false
Does a function like magic_function()
exist in the current distribution of Julia?
PROGRAM_FILE
is""
at the default REPL, and all strings contain""
. There may be other path-based false-positives, too. – Ridenhour