1

I want to ask the user for inputs then store all inputs into a list. The inputs are going to be exactly the same spelling as the functions that I've defined.

inp =  raw_input("functions you want to execute, sep by commas:")
alist = []
for j in inp.split(','):
    alist.append(j)
def func1():
    print 'FUNCTION 1'

def func2():
    print 'FUNCTION 2'

def func3():
    print 'FUNCTION 3'

for i in alist:
    eval(i+'()') #I want to do this but all at the same time

In this case, when asked for input, and I want all 3 functions to be executed, the list is going to look like this:

['func1','func2','func3']

What I want to do is to execute them all at the same time.

I have considered multiprocessing, but I don't know how to do it from a list.

Also, please do not lecture me about my usage of eval(), this code is for molecular dynamics simulation.

  • 1
    Create a process for each func, then after all process objects are constructed (, initialized and so on..) start them. But given the fact that your funcs are very short, most likely one will end before the another is started. As for getting the object (from its name), you could use smth like: `globals()["func1"]()` (this also calls it), depending on how/where the funcs are defined. – CristiFati May 29 '18 at 09:30
  • 1
    Please don't lightheartedly use `eval`: https://stackoverflow.com/q/1832940/1025391 – moooeeeep May 29 '18 at 09:30

1 Answers1

1

You can use the multiprocessing module

from multiprocessing import Process

def A():
  print("A")

def B():
  print("B")

def runAll(fns):
  proc = []
  for fnName in fns:
    fn = globals()[fnName]
    p = Process(target=fn)
    p.start()
    proc.append(p)
  for p in proc:
    p.join()

Then you call them like so:

runAll(['A','B'])

If the functions are not defined in the same module then replace the globals line (globals()...) with:

fn = getattr(module, fnName)

Try it here: Repl.it


As a side note, allowing users to invoke arbitrary functions is a bad idea (security-wise). You could instead explicitly only accept actions from a list of predefined strings.

ᴘᴀɴᴀʏɪᴏᴛɪs
  • 7,169
  • 9
  • 50
  • 81