Call a Python function with arguments based on user input
<p>I would like to call a function from a user input, but include arguments in the parenthesis.  For example, if I have a function that takes one argument:</p>

<pre><code>def var(value):
    print(value)
</code></pre>

<p>I would like to ask the user for a command and arguments, then call the function with the arguments:</p>

<pre><code>Input Command: var("Test")
Test
</code></pre>

<p>Split the function name from the arguments.  Look up the function by name using a predefined map.  Parse the arguments with <code>literal_eval</code>.  Call the function with the arguments.</p>

<pre><code>available = {}

def register_func(f):
    available[f.__name__] = f

@register_func
def var(value):
    print(value)

from ast import literal_eval

def do_user_func(user_input):
    name, args = user_input.split('(', 1)
    return available[name](*literal_eval('(' + args[:-1] + ',)'))

do_user_func("var('test')")  # prints "test"
</code></pre>

<p>This is still incredibly brittle, any invalid input will fail (such as forgetting parentheses, or an invalid function name).  It's up to you to make this more robust.</p>

<p><code>literal_eval</code> is still somewhat unsafe on untrusted input, as it's possible to construct small strings that evaluate to large amounts of memory. <code>'['  * 10 + ']' * 10</code>, for a safe but demonstrative example.</p>

<p>Finally, <strong>do not use <code>eval</code> on untrusted user input</strong>. <a href="http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html" rel="nofollow">There is no practical way to secure it from malicious input.</a>  While it will evaluate the nice input you expect, it will also evaluate code that, for example, will delete all your files.</p>

python