Python从给定参数简单调用函数



我正在学习python,我得到了这个错误:

getattr(args, args.tool)(args)
AttributeError: 'Namespace' object has no attribute 'cat'

如果我这样执行我的脚本:

myscript.py -t cat

我想要的是打印

Run cat here

这是我的完整代码:

#!/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 !"    

谢谢你的帮助:D

EvenLisle的答案给出了正确的想法,但您可以通过使用arg.tools作为globals()的密钥来轻松地将其推广。此外,为了简化验证,您可以使用add_argumentchoices参数,以便了解args.tool的可能值。如果有人为-t命令行选项提供了dog、cat或fish以外的参数,则解析器将自动通知他们使用错误。因此,您的代码将变为:

#!/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)

这:

def cat(args):
print 'Run cat here'
if "cat" in globals():
globals()["cat"]("arg")

将打印"Run cat here"。您应该考虑养成将函数定义放在文件顶部的习惯。否则,上面的代码片段就不会起作用,因为函数cat还不在globals()返回的字典中。

最新更新