Rscript detect if R script is being called/sourced from another script

后端 未结 1 979
清歌不尽
清歌不尽 2021-01-12 04:28

I have a written a script that when it is sourced checks if the script is being run interactively using interactive(). If it is run interactively, it does not s

相关标签:
1条回答
  • 2021-01-12 05:21

    EDIT

    Okay, this is a LOT more like python's __name__ trick. (Previous answer below, kept for historical reasons.)

    function1 <- function(etc,etc) {}
    function2 <- function(etc,etc) {}
    
    if (sys.nframe() == 0L) {
        library(optparse)
        # ...
    }
    

    It is about as minimalist as one could hope for, does not require the sourceing script to know anything about it, and seems to work well even when nested.

    Other possible mechanisms could be used (additional functions required) by looking at script names, per Rscript: Determine path of the executing script. Many plausible (some really good) solutions exist there, but they all require a pre-defined function not defined in a base package (or non-trivial code included in the script to be sourced). If you want to "assume package X is installed", then your script becomes potentially non-portable.


    (Previous answer, I suggest you use above.)

    I'll throw this out as a hack ... it's only slightly less janky than your workaround, but it relies on the calling script knowing something of what the called script is testing for.

    If the calling script sets a variable:

    BEING_SOURCED_FROM_SOMEWHERE <- TRUE
    

    then the called script can check for it:

    function1 <- function(etc,etc) {}
    function2 <- function(etc,etc) {}
    
    if (! exists("BEING_SOURCED_FROM_SOMEWHERE")) {
      library(optparse)
      # ...
    }
    

    I don't like it. It isn't as flexible as python's

    if __name__ == "__main__":
        import optparse
        # ...
    

    But I think I dislike it less than your use of save and load for function definitions.

    0 讨论(0)
提交回复
热议问题