docopt.R icon indicating copy to clipboard operation
docopt.R copied to clipboard

Possibility to source a script and passing arguments to it

Open blaiseli opened this issue 9 years ago • 2 comments

Is it possible to pass arguments to a script using docopt when sourcing this script?

I tried redefining commandArgs as suggested in http://stackoverflow.com/a/14526329/1878788, but this fails.

for instance, my docopt text (named doc) contains the following rule:

-o, --out_dir <out_dir>  out_dir

If, in my interactive R session, I redefine commandArgs as follows:

 commandArgs <- function() {c("--out_dir", "interactive_session")}

and then source my script, when I examine the result of docopt(doc), I see the following:

$`--out_dir`
NULL

Any help appreciated.

blaiseli avatar Sep 28 '16 10:09 blaiseli

It seems that docopt completely ignores commandArgs(). I solved my problem by modifying the script. I decided that if the first element of the output of commandArgs() was a special magic word, then the docopt(doc) results should be ignored and the rest of commandArgs() should be parsed instead. Ugly hack, but works for my purpose. If you have better propositions, don't hesitate.

blaiseli avatar Sep 29 '16 08:09 blaiseli

redefining commandArgs() in your global environment won't change which commandArgs function is found by docopt. The symbol commandArgs is resolved in the namespace of the docopt package, not in your global environment. What you probably want to do is mask the docopt function in your global environment, though it's arguably an anti-pattern and probably a bad idea. In any case, this is how you could do it:

formals(docopt)$args <- function() c("--out_dir", "interactive_session")

t-kalinowski avatar Oct 25 '19 23:10 t-kalinowski