Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AttributeError: 'Namespace' object has no attribute 'check'

Tags:

python

I am trying to run a python script on the command line with different arguments to it. There is one positional paramter ( num ) and others are optional parameters. I try to run [ python newping.py 10 -c ] but get the below error. Is there any error that I am not able to figure out?

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",action="store_true", help="current appliance password. Between 8 and 15 characters, lower case, upper case and numbers")
 arg3 = parser.add_argument("-i", "--ignore",help="ignore the args",action="store_true", dest="ignore")
 arg4 = parser.add_argument("-c", "--check", help="performance metrics",action="store_true", dest="performance")
 arg5 = parser.add_argument("-m", "--node/model",dest="Node_Model",help="Type of the Model",action="store_true")
 parser.add_argument("-pf", "--permfile", help="increase output verbosity",action="store_true")
 args = parser.parse_args()

 result = fibo(args.num)
 print("The "+str(args.num)+"th fibonacci number is "+str(result))

 if args.permfile:

        for x in range(1,len(vars(args))):
            value = locals()["arg"+str(x)]
            print(value.dest+ " "+ value.help)

 if args.password:
    print("I am asking for the password")

 if args.ignore:
    print("This is to ignore the command")

 if args.check:
    print("Check the performance of the server")


 if __name__ == '__main__':
    Main()


 Output :
 The 10th fibonacci number is 55
 Traceback (most recent call last):
 File "newping.py", line 41, in <module>
  Main()
 File "newping.py", line 36, in Main
   if args.check:
   AttributeError: 'Namespace' object has no attribute 'check'
like image 931
Goutam Avatar asked May 09 '16 22:05

Goutam


Video Answer


1 Answers

When you created the argument

arg4 = parser.add_argument("-c", "--check", help="performance metrics",
    action="store_true", dest="performance")

The dest paramter told argparse to use a variable named performance, not check. Change your code to:

if args.performance:
    print("Check the performance of the server")

or remove the dest param.

Python style guides suggest that you limit lines to 80 characters and thats helpful when posting to SO so that we don't have to scroll to see the code.

like image 78
tdelaney Avatar answered Oct 09 '22 05:10

tdelaney