I want to call that function by extracting the first word from the string. For example my string is like:
"my_func arg_1 arg_2"
# ^ ^ ^ second argument of function
# ^ ^ first argument of function
# ^ name of the function
where my_func
is a name of the function already defined.
Based on the above mention string, I want to dynamically execute the my_func
function. So, my function call should be like:
my_func(arg_1, arg_2)
Currently I am trying to achieve this via using eval
:
eval(command.split(' ', 1)[0])
How can I achieve this?
Best Answer
You may use
locals()
(orglobals()
) to fetch the reference of function based on string. Below is the sample example:Now, pass the function string as a key to the
locals()
dict with*params
as argument to the function as: