Search code examples
pythonr

Is if(interactive()) an R equivalent to the pythonic “if __name__ == ”__main__“: main()”?


I would like R scripts to have a main() function that gets executed while in interactive mode. But the main() function should not be executed while sourcing the file.

There is already a question about this and a very good answer suggests using the interactive() function. However this doesn't work for me. I don't have enough reputation points to comment or answer in that question. So I ask the question here again.

I write this in script_1.r

if(interactive()){
  your main code here
}
  • If I use knitr to waive a html or pdf document, sourcing the script. This code under if(interactive()) won't be executed. This is good for me, that's what I want.

  • My problem is that if I source("script_1.r") from script_2.r in interactive mode, it will still run the code under this if(interactive()) part.

    • Is there a way to prevent the if(interactive()) part to run when sourcing it from another script?
  • I would like the if(interactive()) code to run only when calling that script directly.


Solution

  • The best way to get the kind of control you're looking for is to use options.

    For instance, 'script.r' would look like this:

    main <- function() {
        message('main!')
    }
    
    if (getOption('run.main', default=TRUE)) {
       main()
    }
    

    If you are sourcing the file in interactive mode and don't want main to execute, simply call options(run.main=FALSE) before you call source. If you are using the script with knitr and you want main to execute, don't set the option, and it will default to TRUE. Or if you don't want the main to run with knitr, call options(run.main=FALSE) before calling it.