Reputation: 49
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.
Upvotes: 1
Views: 65
Reputation: 7529
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.
Upvotes: 1