如何从 ArgumentParser 实例中列出所有已注册的参数? [英] How can I list all registered arguments from an ArgumentParser instance?
本文介绍了如何从 ArgumentParser 实例中列出所有已注册的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
找不到任何现有的方法,所以我想知道是否有黑客攻击?
解决方案
有一个 hack;您可以使用未记录的属性 parser._actions
列出所有已注册的操作:
使用该属性的风险由您自行承担;这些内部结构在未来版本中可能会发生变化.
Couldn't find any existing method for it so I wonder if there is a hack?
解决方案
There is a hack; you can list all registered actions using the undocumented attribute parser._actions
:
>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
_StoreAction(option_strings=['--foo'], dest='foo', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)
>>> parser.add_argument('--bar')
_StoreAction(option_strings=['--bar'], dest='bar', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)
>>> parser.add_argument('spam')
_StoreAction(option_strings=[], dest='spam', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)
>>> parser.add_argument('eggs')
_StoreAction(option_strings=[], dest='eggs', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)
>>> parser._actions
[_HelpAction(option_strings=['-h', '--help'], dest='help', nargs=0, const=None, default='==SUPPRESS==', type=None, choices=None, help='show this help message and exit', metavar=None), _StoreAction(option_strings=['--foo'], dest='foo', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None), _StoreAction(option_strings=['--bar'], dest='bar', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None), _StoreAction(option_strings=[], dest='spam', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None), _StoreAction(option_strings=[], dest='eggs', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)]
Using the attribute is at your own risk; these internals are subject to change in future versions.
这篇关于如何从 ArgumentParser 实例中列出所有已注册的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文