How to get available flags out of an ArgumentParser object?

可紊 提交于 2019-12-25 05:05:14

问题


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?


回答1:


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']
>>> 



回答2:


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.



来源:https://stackoverflow.com/questions/14913855/how-to-get-available-flags-out-of-an-argumentparser-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!