Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python argparse toggle flags

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.

like image 680
nbaztec Avatar asked Jul 16 '12 15:07

nbaztec


People also ask

How do you add an optional argument in Argparse?

To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.

What is Store_true in Python?

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.

What does Nargs do in Argparse?

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.

What does parse_args return?

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.


1 Answers

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)
like image 184
ecatmur Avatar answered Sep 21 '22 05:09

ecatmur