Reputation: 2231
I am learning python, I get this error:
getattr(args, args.tool)(args)
AttributeError: 'Namespace' object has no attribute 'cat'
If I execute my script like this:
myscript.py -t cat
What i want is print
Run cat here
Here is my full code:
#!/usr/bin/python
import sys, argparse
parser = argparse.ArgumentParser(str(sys.argv[0]))
parser.add_argument('-t', '--tool', help='Input tool name.', required=True, choices=["dog","cat","fish"])
args = parser.parse_args()
# Call function requested by user
getattr(args, args.tool)(args)
def dog(args):
print 'Run something dog here'
def cat(args):
print 'Run cat here'
def fish(args):
print 'Yes run fish here'
print "Bye !"
Thanks, for your help :D
Upvotes: 0
Views: 52
Reputation: 2659
EvenLisle's answer gives the correct idea, but you can easily generalize it by using arg.tools
as the key to globals()
. Moreover, to simplify validation, you can use the choices
argument of add_argument
so that you know the possible values of args.tool
. If someone provides an argument other than dog, cat, or fish for the -t command line option, your parser will automatically notify them of the usage error. Thus, your code would become:
#!/usr/bin/python
import sys, argparse
parser = argparse.ArgumentParser(str(sys.argv[0]))
parser.add_argument('-t', '--tool', help='Input tool name.', required=True,
choices=["dog","cat","fish"])
args = parser.parse_args()
def dog(args):
print 'Run something dog here'
def cat(args):
print 'Run cat here'
def fish(args):
print 'Yes run fish here'
if callable(globals().get(args.tool)):
globals()[args.tool](args)
Upvotes: 1
Reputation: 4812
This:
def cat(args):
print 'Run cat here'
if "cat" in globals():
globals()["cat"]("arg")
will print "Run cat here". You should consider making a habit of having your function definitions at the top of your file. Otherwise, the above snippet would not have worked, as your function cat
would not yet be in the dictionary returned by globals()
.
Upvotes: 0