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

时间:2015-04-23 20:34:48

标签: 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

2 个答案:

答案 0 :(得分:1)

EvenLisle的回答提供了正确的想法,但您可以使用arg.tools作为globals()的关键字来轻松概括。此外,为简化验证,您可以使用choices的{​​{1}}参数,以便了解add_argument的可能值。如果有人为-t命令行选项提供了除dog,cat或fish之外的参数,则解析器将自动通知它们使用错误。因此,您的代码将成为:

args.tool

答案 1 :(得分:0)

此:

public bool FitsCheckBoxCriteria(LubeTask tasks)
{
    bool noShutdownReqChecked = (bool)NoShutDownRequiredCheckBox.IsChecked;
    bool activeChecked = (bool)ActiveRequiredCheckBox.IsChecked;

    bool active = tasks.Active == "YES" ? true : false;
    bool shutdownReq = tasks.ShutdownRequired == "YES" ? true : false;

    // if neither checkboxes are checked, show everything
    bool showEverything = !noShutdownReqChecked && !activeChecked;

    // if both are checked, only show activeChecked non-shutdown tasks
    bool showActiveNonShutdown = activeChecked && noShutdownReqChecked && active && !shutdownReq;

    // if activeChecked is checked but shudown isn't, display all activeChecked
    bool showActive = activeChecked && !noShutdownReqChecked && active;

    // if non-shutdown is chceked but activeChecked isn't, display all non-shutdown tasks
    bool showNonShutdown = noShutdownReqChecked && !activeChecked && !shutdownReq;

    return showEverything || showActiveNonShutdown || showActive || showNonShutdown;
}

将打印"在这里运行猫"。您应该考虑养成将函数定义放在文件顶部的习惯。否则,上面的代码段就不起作用,因为您的函数def cat(args): print 'Run cat here' if "cat" in globals(): globals()["cat"]("arg") 还不在cat返回的字典中。