从Argparse-python中的parse.add_参数中提取值
我使用Argparse作为命令行实用程序执行的一种手段。我定义了各种参数(下面显示了其中的两个)。我需要将参数名称、帮助和类型存储在数据库中各自的列中 我不知道如何从每个parse.add_参数中提取这三个参数并将其保存在某个数组/列表中。如果你能分享任何意见,那会很有帮助从Argparse-python中的parse.add_参数中提取值,python,argparse,Python,Argparse,我使用Argparse作为命令行实用程序执行的一种手段。我定义了各种参数(下面显示了其中的两个)。我需要将参数名称、帮助和类型存储在数据库中各自的列中 我不知道如何从每个parse.add_参数中提取这三个参数并将其保存在某个数组/列表中。如果你能分享任何意见,那会很有帮助 parser.add_argument("num",help="The fibnocacci number to calculate:", type=int) # how to take the strings
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")
其他人认为您需要解析commandline的结果,即
args
名称空间中的值。但是我怀疑您想要操作
对象,该对象由add\u参数
方法定义
在交互式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)]
您需要检查argparse.py
文件中的类定义,以了解这些属性。当我执行arg1.type时,我得到的是而不是int?我通过print(arg1.type)
得到它int
既是一个类,也是一个生成整数的函数。
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}