How to handle calling functions from cli

Chris Angelico rosuav at gmail.com
Fri Feb 24 23:43:20 CET 2012


On Sat, Feb 25, 2012 at 9:16 AM, Rodrick Brown <rodrick.brown at gmail.com> wrote:
> m = { 'a': 'checkDisks()',
>          'b': 'checkMemSize()',
>          'c': 'checkBondInterfaces()'
>    }
>
>    runlist = [ c for c in m.keys() if c not in r.d ]
>    for runable in runlist:
>        eval(m[runable])

It's a reasonable technique. Does have the downside that your
functions will be called in an unpredictable order, though. If that's
a problem, replace the dictionary with a tuple of tuples (and then
just take off the .items() in the list comp).

I would be inclined to avoid eval, especially if none of your
functions need parameters. Just hold references to the functions
themselves:

checks = {
         'a': checkDisks,
         'b': checkMemSize,
         'c': checkBondInterfaces, # note that this comma is perfectly
legal - all these lines can be structured identically
}

[func[option]() for option,func in checks.items() if option not in r.d]

ChrisA



More information about the Python-list mailing list