Reputation: 94267
Python has this handy construct:
def do_stuff():
whatever
if __name__ == "__main__":
do_stuff(()
so that if the file is run from the command line with python foo.py
or ./foo.py
and the appropriate shebang line, then the __name__
variable is set to __main__
and the file runs as a script. However you can also do from foo import do_stuff
from an interactive shell or other python code and run do_stuff
from there. The same script file is then acting as a module instead of as a script.
Can I do something similar in littler
scripts? Something like foo.R
being:
#!/bin/env r
do_stuff = function(){
whatever
}
if(?run as r command_line?){
do_stuff()
}
Then I can source("foo.R")
and that would define do_stuff
(in my default global environment, but we'll gloss over that for a bit).
One possible key is the presence of _
in the environment when running under littler
(set to the script name) but something a little stronger might be nice.
Upvotes: 4
Views: 117
Reputation: 78832
Something like this should work:
#!/usr/local/bin/r --vanilla
doStuff <- function(print_me) {
print(print_me)
}
if (!interactive()) {
if (exists("argv")) {
if (!is.null(argv) && length(argv)>0) {
doStuff(argv[1])
}
}
}
Upvotes: 3