trevorld / r-argparse

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

Nicer error for invalid arguments #40

Closed dariober closed 1 year ago

dariober commented 2 years ago

It's no biggie at all but if easy to fix it would be nice... Passing an invalid argument gives a meaningful error plus some extra error from R that clutters the message. For example:

#!/usr/bin/env Rscript

library(argparse)

parser <- ArgumentParser()
parser$add_argument('--param', type= 'integer')
xargs <- parser$parse_args()

Run with an invalid argument:

./script.R --param foo
Error in .stop(output, "parse error:") : parse error:
usage: ./script.R [-h] [--param PARAM]
./script.R: error: argument --param: invalid int value: 'foo'
Calls: <Anonymous> -> parse_args_output -> .stop
Execution halted

It would be slightly preferable if the message was just:

usage: ./script.R [-h] [--param PARAM]
./script.R: error: argument --param: invalid int value: 'foo'

sessionInfo()
R version 4.1.2 (2021-11-01)
Platform: x86_64-conda-linux-gnu (64-bit)
Running under: Ubuntu 18.04.6 LTS

Matrix products: default
BLAS/LAPACK: /home/dario/miniconda3/envs/tritume/lib/libopenblasp-r0.3.18.so

locale:
 [1] LC_CTYPE=en_GB.UTF-8       LC_NUMERIC=C               LC_TIME=en_GB.UTF-8        LC_COLLATE=en_GB.UTF-8     LC_MONETARY=en_GB.UTF-8    LC_MESSAGES=en_GB.UTF-8    LC_PAPER=en_GB.UTF-8       LC_NAME=C                  LC_ADDRESS=C              
[10] LC_TELEPHONE=C             LC_MEASUREMENT=en_GB.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] argparse_2.1.5

loaded via a namespace (and not attached):
[1] compiler_4.1.2 R6_2.5.1       jsonlite_1.8.0
trevorld commented 1 year ago

After 2cf5429 the message (with default R error handler) is now:

usage: test.R [-h] [--param PARAM]
test.R: error: argument --param: invalid int value: 'foo'
Execution halted

To get rid of the trailing "Execution halted" you'll need to manually set your own error handler e.g.

#!/usr/bin/env Rscript

library(argparse)
if (!interactive())
    options(error=function(e) quit('no', status = 1, runLast = FALSE))

parser <- ArgumentParser()
parser$add_argument('--param', type= 'integer')
xargs <- parser$parse_args()

will get you to

usage: test.R [-h] [--param PARAM]
test.R: error: argument --param: invalid int value: 'foo'
trevorld commented 1 year ago

After 1a20610 you should not need to manually set an error handler just to suppress the final "Execution halted" message.