使用Argparse-python时,将字符串类型转换为Parser对象



我正在尝试使用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)]

最新更新