A Parser R6 object wraps a Python argparse argument parser.
Objects of this class are returned by ArgumentParser() and by the
add_parser() method of Subparsers objects.
If a parse error occurs (or help or version information is requested) then in an interactive session an error is raised whereas in a non-interactive session (i.e. a script) a message is printed and R exits.
References
Python's argparse documentation:
https://docs.python.org/3/library/argparse.html
Methods
Parser$parse_intermixed_args()
Parse command line arguments allowing optional and positional arguments to be intermixed.
Usage
Parser$parse_intermixed_args(args = commandArgs(TRUE))Parser$parse_known_args()
Parse command line arguments without raising an error for unrecognized arguments.
Usage
Parser$parse_known_args(args = commandArgs(TRUE))Parser$parse_known_intermixed_args()
Parse command line arguments allowing optional and positional arguments to be intermixed and without raising an error for unrecognized arguments.
Usage
Parser$parse_known_intermixed_args(args = commandArgs(TRUE))Parser$add_argument()
Define how a single command line argument should be parsed.
Parser$add_argument_group()
Create an argument group. Arguments added to the group are displayed together in the help message.
Arguments
...Arguments cleaned and passed to Python's
add_argument_group()method such astitleanddescription.
Returns
An ArgumentGroup object.
Parser$add_mutually_exclusive_group()
Create a mutually exclusive group. Only one of the arguments added to the group may be present on the command line.
Arguments
requiredIf
TRUEthen exactly one of the arguments in the group must be present on the command line.
Returns
A MutuallyExclusiveGroup object.
Parser$add_subparsers()
Add support for sub-commands.
Arguments
...Arguments cleaned and passed to Python's
add_subparsers()method such astitle,description,help,dest, andrequired.
Returns
A Subparsers object.
Parser$new()
Create a new Parser object.
Users should not call this directly but instead use ArgumentParser().
Usage
Parser$new(python_code, name)Examples
run_example <- argparse:::detects_python()
if (run_example) {
parser <- ArgumentParser(description = "Process some integers")
parser$add_argument("integers", metavar = "N", type = "integer",
nargs = "+", help = "an integer for the accumulator")
parser$add_argument("--sum", dest = "accumulate", action = "store_const",
const = "sum", default = "max",
help = "sum the integers (default: find the max)")
parser$print_usage()
}
#> usage: PROGRAM [-h] [--sum] N [N ...]
if (run_example) {
args <- parser$parse_args(c("--sum", "1", "2", "3"))
print(args)
}
#> $accumulate
#> [1] "sum"
#>
#> $integers
#> [1] 1 2 3
#>
if (run_example) {
args <- parser$parse_known_args(c("--sum", "1", "2", "--unknown"))
print(args)
}
#> [[1]]
#> [[1]]$integers
#> [1] 1 2
#>
#> [[1]]$accumulate
#> [1] "sum"
#>
#>
#> [[2]]
#> [1] "--unknown"
#>