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.