0

I'm using the argparse module for this python project. I'm looking to get the available flags out of an ArgumentParser object before calling parse_args(). Anyone have any ideas?

2 Answers 2

3

Got this from the source code of add_argument():

>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-v', '--verbosity', help='more debug info', action='store_true')
_StoreTrueAction(option_strings=['-v', '--verbosity'], dest='verbosity', nargs=0, const=True, default=False, type=None, choices=None, help='more debug info', metavar=None)
>>> parser._option_string_actions.keys()
['-v', '-h', '--verbosity', '--help']
>>> 
1

I was trying to solve this the other day and I never got a satisfactory answer other than the following on from what @vvoody did.

In [117]: map(lambda x : x.dest,parser._actions)
Out[117]: ['help', 'verbosity']

The benefit is that it removes all the alias -v == --verbosity etc. BUT if you change dest for --verbosity e.g dest='loud' then it returns loud which may or may not be an issue.

Seems an obvious thing for argsparse to provide out of the box.

2
  • 1
    I think vvoody's is closer to what I need. It is sort of weird that we have to access a private method for either of these things though :/
    – sfendell
    Feb 16, 2013 at 22:36
  • 1
    In my case I was trying to set options to default to env vars so that $FOO=bar in the environment would set the dest=foo, whether it was --foo or -f or whatever. Agreed that is seems weird to use private methods to access the data esp. when there can be a mismatch between option and the intenal model help by argparse.
    – sotapme
    Feb 16, 2013 at 22:41

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.