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

时间:2016-04-03 01:35:25

标签: python argparse

我使用Argparse作为命令行实用程序执行的手段。我定义了各种参数(如下所示)。我需要存储参数名称,帮助,在各自的列中键入数据库。

我不确定如何从每个parse.add_argument中提取这三个并将其保存在某个数组/列表中。如果您可以分享任何输入,那将是有帮助的。

     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")

1 个答案:

答案 0 :(得分:0)

其他人认为你想要解析commandlline的结果,即args命名空间中的值。但我怀疑你想要Action方法定义的add_argument对象

在交互式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子类(基于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文件中的类定义以了解这些属性。