trevorld / r-argparse

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

Unhelpful JSON error message when accidentally giving ArgumentParser an unnamed argument and parser has no positional/optional arguments #15

Closed capnrefsmmat closed 6 years ago

capnrefsmmat commented 7 years ago

With the following reasonable-looking argparse code:

library(argparse)
parser <- ArgumentParser("command_name")
args <- parser$parse_args()

we get the message

Error in rjson::fromJSON(paste(output, collapse = "")) : 
  unexpected character 'F'

because parser$python_code is

[1] "import argparse"                                                 
[2] "try:"                                                            
[3] "    import json"                                                 
[4] "except ImportError:"                                             
[5] "    import simplejson as json"                                   
[6] ""                                                                
[7] "parser = argparse.ArgumentParser(prog='PROGRAM', 'command_name')"

which is a SyntaxError, because positional arguments cannot come after keyword arguments.

First, it'd be helpful to present SyntaxErrors to the user instead of the JSON error that results from trying to parse them. Second, perhaps it's incorrect for argparse to paste the user-provided arguments after the prog= argument it provides?

Thanks!

trevorld commented 7 years ago

I agree that the error message isn't very helpful.

All arguments to ArgumentParser are supposed to be keyword arguments, so pasting afterwards or before the prog= argument shouldn't matter since user should always supply each argument name in that function. Just like in python you need to use add_argument if you want to add a (positional) argument:

 library("argparse")
 parser <- ArgumentParser(description="This program does this cool thing")
 parser$add_argument("command_name")
 args <- parser$parse_args()