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>I am going to post this solution as an alternative, under the assumption that you are dealing with <em>simple</em> inputs such as: </p>

<pre><code>var(arg)
</code></pre>

<p>Or, a single function call that can take a list of positional arguments. </p>

<p>By using <code>eval</code> it would be a horrible un-recommended idea, as already mentioned. I think that is the security risk you were reading about.</p>

<p>The ideal way to perform this approach is to have a dictionary, mapping the string to the method you want to execute.</p>

<p>Furthermore, you can consider an alternative way to do this. Have a space separated input to know how to call your function with arguments. Consider an input like this: </p>

<pre><code>"var arg1 arg2"
</code></pre>

<p>So when you input that: </p>

<pre><code>call = input().split()
</code></pre>

<p>You will now have: </p>

<pre><code>['var', 'arg1', 'arg2']
</code></pre>

<p>You can now consider your first argument the function, and everything else the arguments you are passing to the function. So, as a functional example: </p>

<pre><code>def var(some_arg, other_arg):
    print(some_arg)
    print(other_arg)

d = {"var": var}

call = input().split()

d[call[0]](*call[1:])
</code></pre>

<p>Demo: </p>

<pre><code>var foo bar
foo
bar
</code></pre>

python