Declaring main function/entry point in Julia
Asked Answered
M

3

17

Is there a ready or idiomatic way of declaring an entry point in a Julia program (i.e. the equivalent of main in C or the if __name__ == "__main__" construct in Python)?

This seems to be an important functionality in order to write larger pieces of structured code that won't be used in interactive mode but I couldn't find any hints as to how this is accomplished in Julia, if at all (a possible escape route could be writing an arbitrary function to serve as main and then calling it once on the top level at the end of the main module but that's not elegant and maybe not even efficient). TIA.

Mymya answered 24/7, 2014 at 1:30 Comment(2)
Perhaps some incantation using @__FILE__()?Sitsang
I'd recomend a search on julia-usersGrindelia
H
11

When modules are loaded, if they have a function called __init__ it will be called. Does that help?

Hotblooded answered 24/7, 2014 at 20:43 Comment(1)
Yes, this seems to be more or less what I was looking for, thank you.Mymya
R
15

You could write a main function and not call it from the top level of the file. To run the program from the command line you would use julia -L file.jl -e 'main(some,args)'. The -L switch tells Julia to load your file, and then -e tells it to evaluate the following expression. There is also an -E switch that evaluates and prints (I think of it as "evaluating out loud", since capital letters seem "loud").

This has a couple of advantages over C's main or Python's if __name__ == "__main__":

  1. You don't have to have a single entry point! You can evaluate any expression at all after loading your file, so you don't have to cram all your command line functionality into one function.

  2. The calls you write use full Julia syntax, so often you can avoid parsing the arguments. Soemthing like -e main(53) calls main with the integer 53, no need for atoi inside main.

Russia answered 24/7, 2014 at 13:38 Comment(0)
H
11

When modules are loaded, if they have a function called __init__ it will be called. Does that help?

Hotblooded answered 24/7, 2014 at 20:43 Comment(1)
Yes, this seems to be more or less what I was looking for, thank you.Mymya
J
3

If you want to do what the if __name__ == "__main__": idiom in python does, I found that

if !isdefined(Base, :active_repl)
    main()
end

does the trick.

I often find myself wanting to be able to load my main file into a REPL and selectively poke at some of the functions without invoking main or staple a CLI onto a module that is mostly intended as a library module, so I really like this trick from python.

Jaeger answered 12/8, 2020 at 23:10 Comment(1)
Something like this also works function main() # do stuff end if abspath(PROGRAM_FILE) == @__FILE__ main() end see docs.julialang.org/en/v1/manual/faq/…Diversify

© 2022 - 2024 — McMap. All rights reserved.