trevorld / r-argparse

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

How to prevent ArgumentParser from exit in case of wrong arguments? #16

Closed trevorld closed 6 years ago

trevorld commented 7 years ago

A user asks:

Please, let me know if it is possible to prevent ArgumentParser from exiting in case of wrong arguments. For example, throw an exception instead. As I understand, Python parser allows to catch an exception using

try ...
    except SystemExit:

construct.

However, I've not found any similar capability in R. Am I missing something?

trevorld commented 7 years ago

You aren't missing something and exiting after printing a usage message is the desired behavior in the vast majority of command-line applications. As currently coded argparse throws an error when it encounters a help flag or incorrect usage when interactive() == TRUE mode and exits when interactive() == FALSE (i.e. in a typical script). I'm not aware of R allowing one to catch exit calls and didn't see an easy way to spoof interactive so that it returns TRUE when it actually is FALSE.

Depending on your use case one of the other command line parsers for R could work. For example in optparse::parse_args you could set the argument print_help_and_exit to FALSE and getopt doesn't call quit at all (i.e. it makes you call quit it manually). Maybe newer command-line parsing packages like docopt, argparser, as well as at least one other I've forgotten the name of also don't call exit or has an option to turn it off. I'm not sure (haven't looked into it).

trevorld commented 7 years ago

~Actually, on second thought if you were really determined you may be able to manually edit and replace the body of parser$parse_args using R built-ins and regular expressions although forking the package and manually installing your fork would probably be easier.~

trevorld commented 3 years ago