I'm taking a stab at multiprocessing and I need one process to tell the other to run a given function. On the receiving end, I'm trying to figure out how to interpret the message it gets. I could set up a big nest of if/elif to test for every possible function:

def Bacon ():
	print ( "Lean!" )
def Eggs ():
	print ( "Scrambled!" )
def Toast ():
	print ( "Butter!" )

Function = "Eggs"

if Function == "Bacon" :
	Bacon ()
elif Function == "Eggs" :
	Eggs ()
elif Function == "Toast" :
	Toast ()

But it would be a lot nicer if I could just convert the string to a function reference directly. Something like this:

def Bacon ():
	print ( "Lean!" )
def Eggs ():
	print ( "Scrambled!" )
def Toast ():
	print ( "Butter!" )

Function = "Eggs"

Call_Function_From_String ( Function )

Does anyone know if that's possible?

Thanks!

Recommended Answers

All 2 Replies

This type of thing generally used for creating a menu using a dictionary. An example of a menu using eval() to call the function:

def func_1():
   print "     func_1 test"
def func_2():
   print "     func_2 test"
def func_3():
   print "     func_3 test"
def func_4():
   print "     func_4 test"

##----------------------------------------------------------------
##   dictionary = list of function to call and menu choice to print
menu_d = { 1:['func_1()', '1)Load'], 
           2:['func_2()', '2)Save'], 
           3:['func_3()', '3)Add Phone Number'],
           4:['func_4()', '4)View Phone Number'],
           5:["", "5)Exit"]}
choice = 0
while choice != 5:
   print "\nSelect an Option\n"
   for j in range(1, 6):
      print menu_d[j][1]   ## print list's element #1 for key=j

   choice = int(raw_input( "Enter choice, 1-5 " ))
   if choice in menu_d:
      dict_list = menu_d[choice]
      eval(dict_list[0])
      ## eval(menu_d[choice][0])   will also work
print "\nend of program"

This type of thing generally used for creating a menu using a dictionary. An example of a menu using eval() to call the function:

Ah, perfect! Thanks so much! :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.