Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Within a Julia script, can you tell whether the script has been imported or executed directly?

Tags:

julia

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?

like image 259
Ben Hamner Avatar asked Jan 22 '13 15:01

Ben Hamner


1 Answers

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

like image 61
Atsushi Sakai Avatar answered Oct 20 '22 11:10

Atsushi Sakai