Is there any way in argparse to parse flags like [+-]a,b,c,d
?
foo.py +s -b
should store True in the dest
of s
and False in the dest
of b
, much like done by the Windows attrib
or the Linux chmod
.
Currently, I am using 2 separate arguments +s
and -s
with store_true
and store_false
, respectively. But it creates an ugly help with it listing each flag twice (+a & -a)
Another workaround would be to manually parse the extended arg with regex (which somehow seems a lot easier and use custom description, but before doing that I just wanted to look around if there was anything using which I could perform the same thing using argparse itself.
To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.
The store_true option automatically creates a default value of False. Likewise, store_false will default to True when the command-line argument is not present.
The add_argument() method action - The basic type of action to be taken when this argument is encountered at the command line. nargs - The number of command-line arguments that should be consumed. const - A constant value required by some action and nargs selections.
parse_args() returns two values: options, an object containing values for all of your options— e.g. if "--file" takes a single string argument, then options. file will be the filename supplied by the user, or None if the user did not supply that option.
You can do this by passing both -s
and +s
to a single add_argument
call, and using a custom action:
class ToggleAction(argparse.Action):
def __call__(self, parser, ns, values, option):
setattr(ns, self.dest, bool("-+".index(option[0])))
ap = ArgumentParser(prefix_chars='-+')
ap.add_argument('-s', '+s', action=ToggleAction, nargs=0)
ap.parse_args(['+s'])
Namespace(s=True)
ap.parse_args(['-s'])
Namespace(s=False)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With