How to get available flags out of an ArgumentParse

2019-09-02 17:09发布

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条回答
淡お忘
2楼-- · 2019-09-02 17:18

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']
>>> 
查看更多
聊天终结者
3楼-- · 2019-09-02 17:22

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.

查看更多
登录 后发表回答