我正在尝试使用arg1.dest,arg1.help等来检索所有参数信息,以获取从arg1到arg3的所有不同参数。我通过添加arg +“1,2,3”使用for循环,以便我可以在一个循环中检索它,而不是使用不同的insert命令,而我编写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'
答案 0 :(得分:1)
将value = ("arg"+str(x))
更改为value = locals()["arg"+str(x)]
。