Python argparse allows combo flags

Is it possible for argparse to handle merged flags as follows:

app.py -bcda something 

In this case, I would like something be set to -a , and the rest would be kept True. Mostly:

 app.py -b -c -d -a something 

I know that most programs allow this, for example. grep -rEw , but how hard would it be with argparse?

Edit: The answer is that it comes out of the box. I didn’t even bother to try.

+6
source share
2 answers

You can achieve this with store_const:

 parser = argparse.ArgumentParser() parser.add_argument('-a', action='store_const', const=True, default=False) parser.add_argument('-b', action='store_const', const=True, default=False) args = parser.parse_args() 

You can then invoke this from the command line, either using -a -b or using -ab (or -a or -b ).

Edit: and if you want one of the flags to take an argument, you need to pass it as the last element of the chain. Therefore, if a takes an argument, you need to do -bcda something

+3
source

Here is what I found with a little Googling:

Several short options can be combined together using only one - prefix, if only the last parameter (or none of them) requires a Value:

 >>> parser = argparse.ArgumentParser(prog='PROG') >>> parser.add_argument('-x', action='store_true') >>> parser.add_argument('-y', action='store_true') >>> parser.add_argument('-z') >>> parser.parse_args('-xyzZ'.split()) Namespace(x=True, y=True, z='Z') 

http://docs.python.org/dev/library/argparse.html#option-value-syntax

+1
source

All Articles