10

Is it possible for argparse to parse combined flags like this:

app.py -bcda something

In this case, I would want something to be set to -a and the rest would be stored True. Basically:

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

I know most programs allow this, e.g. grep -rEw, but how hard would it be to do this with with argparse?

1
  • 2
    As Chris Barker noted, the answer is to use -bcda instead of -abcd. Combining is something that works out of the box. Commented Jan 22, 2014 at 15:29

2 Answers 2

7

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()

Then you can call this from the command line either with -a -b or with -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 item of the chain. So if a takes an argument, you'd need to do -bcda something

Sign up to request clarification or add additional context in comments.

1 Comment

action='store_true is more succinct.
2

Here's what I found with a little Googling:

Several short options can be joined together, using only a single - prefix, as long as only the last option (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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.