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 search for command line arguments. However, if it is not run interactively, it searches for command line arguments and throws an error.
This is normally fine, but sometimes I write a second R script that I want to run independently just to process some data. So Script2 sources Script1, and Script1 detects that it is not being run interactively, and begins searching for command line arguments and throwing errors.
Is there a way besides interactive()
that a script can detect its context? For example, I would want separate behavior when it is being run directly vs when it is being loaded for access to one of its internal functions. With packages I could do something like dplyr::arrange()
to access arrange
without having to load all of dplyr.
EDIT: My current very janky workaround has been to start an interactive session, source Script1, use save.image()
to save the functions, and then in Script2 use load
to load the saved .RData file. But obviously this is not...elegant.
I don't think the exact code I use is that relevant, but including it in case someone feels this is important to the answer...
Stripped down example code:
#!/usr/bin/env Rscript
library(optparse)
function1 <- function(etc,etc) {}
function2 <- function(etc,etc) {}
if(!interactive()) {
# example call
# Rscript create_reference_file.R -c cd4cd8 -o /home/outputfolder/
option_list = list(
make_option(c('-c', '--cell'), type = 'character', default = NULL,
help = 'the name of the cell',
metavar = 'character'),
make_option(c('-o','--outdir'), type = 'character', default = NULL,
help = 'the location where you wish to store your output',
metavar = 'character'),
)
opt_parser <- OptionParser(option_list = option_list)
opt <- parse_args(opt_parser)
function1(opt); function2(opt) # etc etc, I do stuff with the opt inputs
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…