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>Instead of using eval, you can parse it yourself. This way, you have control over how each function should parse/deserialize the user input's arguments.</p>

<pre class="lang-python prettyprint-override"><code>import sys, re

def custom_print(value):
    print value

def custom_add(addends):
    print sum(addends)

def deserialize_print(args):
    # just print it as is
    custom_print(args)

def deserialize_add(args):
    # remove all whitespace, split on commas, parse as floats
    addends = [float(x) for x in re.sub(r"\s", "", args).split(",")]
    # send to custom_add function
    custom_add(addends)

def get_command():
    cmd_input = raw_input("Command: ")
    # -- check that the command is formatted properly
    #    and capture command groups
    match = re.match(r"^([a-zA-Z0-9]+)(\(.*\))?$", cmd_input)
    if match:
        # extract matched groups to separate variables
        (cmd, argstring) = match.groups()

        # strip parenthesis off of argstring
        if argstring:
            args = argstring[1:-1]

        # send the whole argument string to its corresponding function
        if cmd == "print":
            deserialize_print(args)
        elif cmd == "add":
            deserialize_add(args)
        elif cmd == "exit":
            sys.exit()
        else:
            print "Command doesn't exist."
    else:
        print "Invalid command."

    # recurse until exit
    get_command()


# -- begin fetching commands
get_command()
</code></pre>

<hr>

<p>This is a pretty rough setup, although you can get by with some more error checking and improving the deserializing functions and modularizing function additions.</p>

<p>If the decoupled deserialize functions seem too much, you can also just move the deserialization into the custom functions themselves.</p>

python