Python argparse toggle flags

2019-06-16 03:31发布

问题:

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.

回答1:

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)