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?
Official Julia doc suggests this:
if abspath(PROGRAM_FILE) == @__FILE__ # do something only this file is executed. do_something() end
The do_something function is only executed when the code is executed, not when the code is imported from other codes.
Ref:"How do I check if the current file is being run as the main script?" https://docs.julialang.org/en/v1/manual/faq/#How-do-I-check-if-the-current-file-is-being-run-as-the-main-script?-1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With