使用 Argparse 时将字符串类型转换为解析器对象 - python

Typecasting String to Parser object while using Argparse - python

我正在尝试使用 arg1.dest、arg1.help 等检索所有参数信息。对于从 arg1 到 arg3 的所有不同参数。我通过添加 arg + "1,2,3" 来使用 for 循环,这样我就可以在一个循环中检索它,而不是在我稍后编写 sql 代码进行插入时使用不同的插入命令。我在这里面临类型转换错误。 arg1 以前是一个解析器对象,但由于我正在转换为字符串并附加它,所以我无法再访问 arg1.dest 或 arg1.help。

我们有没有办法将大小写输入正确的解析器对象?非常感谢任何意见。

import argparse

def fibo(num):
    a,b = 0,1
    for i in range(num):
        a,b=b,a+b
    return a

def Main():
    parser = argparse.ArgumentParser(description="To the find the fibonacci number of the give number")
    arg1 = parser.add_argument("num",help="The fibnocacci number to calculate:", type=int)
    arg2 = parser.add_argument("-p", "--password", dest="password", help="current appliance password")
    arg3 =parser.add_argument("-i", "--ignore", action="store_true", dest="ignore")
    parser.add_argument("-x", "--dbinsert", help="insert data in db",action="store_true")
    args = parser.parse_args()
    result = fibo(args.num)
    print("The "+str(args.num)+"th fibonacci number is "+str(result))

    if args.dbinsert:
        for x in range(1,len(vars(args))):
            value = ("arg"+str(x))
            print(value.dest)

    if __name__ == '__main__':
        Main()
-----------------------------------------------------------------
When I run : python myping.py 10 --dbinsert
Output : The 10th fibonacci number is 55
Traceback (most recent call last):
 File "myping.py", line 42, in <module>
   Main()
 File "myping.py", line 34, in Main
  print(value.dest)
 AttributeError: 'str' object has no attribute 'dest'

value = ("arg"+str(x)) 更改为 value = locals()["arg"+str(x)]