I am pretty excited to have found Jeff and Dirk's application littler to run R functions from terminal. ¡kudos!
Since then, I have been able to pass my functions to my development team and have them running in other servers.
My question is about it's deployment. Before passing it to others, I try it out in my computer and prepare it with RStudio... (also kudos).
I was wondering if there's a command to run in the script on which I can tell if the function is run from the command or if it's been executed with R.
Thanks.
I don’t know whether there’s a littler specific answer. But in general it is impossible (or very hard) in R to determine how the code is run, which was one of the motivations for my work on modules.
The only thing R knows is whether the code is being run in an interactive shell (via interactive()
).
With modules, you can test whether module_name()
is set, analogous to Python’s __name__
:
if (is.null(module_name()) && ! interactive()) {
# Stand-alone, execute main entry point
}
if (! is.null(module_name())) {
# Code is being loaded as a module.
}
I’ve written a small wrapper based on this which I’m using to write my command line applications. For instance, a very simple cat
-like application would look as follows:
#!/usr/bin/env Rscript
sys = modules::import('sys')
sys$run({
if (length(sys$args) == 0) {
message('Usage: ', script_name(), ' filename')
sys$exit(1)
}
input = sys$args[1]
cat(readLines(input))
})