kirakun kirakun - 6 months ago 49
Python Question

Invoking top-level function by name in Python

How can I invoke a top-level function by name? For example,

#!/usr/bin/env python

import sys

def foo():
print 'foo'

def bar():
print 'bar'

# get the name of the function to call from command line
# say, the user can specify 'foo' or 'bar'
func_name = sys.argv[1]

# how do I invoke the function by func_name?
getattr(__main__, func_name) # NameError: global name '__main__' is not defined


The easiest way is to use globals


You can also get the current module object by looking it up in sys.modules.

getattr(sys.modules[__name__], func_name)()