trevorld / r-argparse

command-line optional and positional argument parser
GNU General Public License v2.0
103 stars 11 forks source link

Customised help function instead of default help message #47

Closed Adnanhashim closed 1 year ago

Adnanhashim commented 1 year ago

I have following R script

library(argparse)
library(crayon)

# Define the help message
help_message <- function() {
    cat("\n")
    cat(crayon::bold("Usage:   This is help function\n"))

}

# Define the command line arguments

parser <- ArgumentParser()
parser$add_argument("-f1", "--file1", dest = "file1")
parser$add_argument("-f2", "--file2", dest = "file2")

args <- parser$parse_args() # Parse the command line arguments

if (is.null(args$file1)) {
  cat(crayon::red("\nERROR: Missing argument -f1/--file1\n"))
  help_message()
  q(status = 1)
}

if (is.null(args$file2)) {
  cat(crayon::red("\nERROR: Missing argument -f2/--file2\n"))
  help_message()
  q(status = 1)
}

When I use Rscript test1.R (without any command line argument), I get output from my customised help_message()

ERROR: Missing argument -f1/--file1

Usage:   This is help function

But when I use Rscript test1.R -h, I get default help function output

usage: test1.R [-h] [-f1 FILE1] [-f2 FILE2]

optional arguments:
  -h, --help            show this help message and exit
  -f1 FILE1, --file1 FILE1
  -f2 FILE2, --file2 FILE2

If I use Rscript test1.R -f1, I get following output

usage: test1.R [-h] [-f1 FILE1] [-f2 FILE2]
test1.R: error: argument -f1/--file1: expected one argument

I want to get output from customised help_message in all the cases.

trevorld commented 1 year ago

In this particular case setting nargs = "?" should do what you want (don't trigger an {argparse} ERROR if -f1 or -f2 is missing a file):

parser$add_argument("-f1", "--file1", dest = "file1", nargs = "?")
parser$add_argument("-f2", "--file2", dest = "file2", nargs = "?")