从 Argparse 中的 parse.add_argument 中提取值 - python

Extract values from parse.add_argument in Argparse - python

我正在使用 Argparse 作为命令行实用程序执行的方式。我定义了各种参数(下面显示了其中的几个)。我需要在数据库中的相应列中存储参数名称、帮助、类型。

我不确定如何从每个 parse.add_argument 中提取这三个并将其保存在某些 array/list 中。如果您可以分享任何意见,那将会很有帮助。

     parser.add_argument("num",help="The fibnocacci number to calculate:", type=int)  # how to take the strings on the command line and turn them into objects
     parser.add_argument("-f","--file",help="Output to the text file",action="store_true")

其他人认为您想要解析命令行的结果,args 命名空间中的值。但我怀疑您想要 add_argument 方法

定义的 Action 对象

在交互式 shell 中,我可以将解析器定义为:

In [207]: parser=argparse.ArgumentParser()

In [208]: arg1= parser.add_argument("num",help="The fibnocacci number to calculate:", type=int) 

In [209]: arg2=parser.add_argument("-f","--file",help="Output to the text file",action="store_true")

In [210]: arg1
Out[210]: _StoreAction(option_strings=[], dest='num', nargs=None, const=None, default=None, type=<type 'int'>, choices=None, help='The fibnocacci number to calculate:', metavar=None)

In [211]: arg2
Out[211]: _StoreTrueAction(option_strings=['-f', '--file'], dest='file', nargs=0, const=True, default=False, type=None, choices=None, help='Output to the text file', metavar=None)

In [212]: parser._actions
Out[212]: 
[_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=[], dest='num', nargs=None, const=None, default=None, type=<type 'int'>, choices=None, help='The fibnocacci number to calculate:', metavar=None),
 _StoreTrueAction(option_strings=['-f', '--file'], dest='file', nargs=0, const=True, default=False, type=None, choices=None, help='Output to the text file', metavar=None)]

add_argument 创建一个 Action subclass(基于 action 参数)。您可以将其保存在您自己的变量中,或者在解析器的 _actions 列表中找到它。

打印它会显示它的一些属性,但您可以检查甚至更改更多属性。

In [213]: arg1.help
Out[213]: 'The fibnocacci number to calculate:'

In [214]: arg1.type
Out[214]: int

In [215]: arg1.dest
Out[215]: 'num'

In [217]: vars(arg1)
Out[217]: 
{'choices': None,
 'const': None,
 'container': <argparse._ArgumentGroup at 0x8f0cd4c>,
 'default': None,
 'dest': 'num',
 'help': 'The fibnocacci number to calculate:',
 'metavar': None,
 'nargs': None,
 'option_strings': [],
 'required': True,
 'type': int}

您需要检查 argparse.py 文件中的 class 定义才能理解这些属性。