Skip to content Skip to sidebar Skip to footer

Passing Arguments To Python Eval()

I'm doing genetic programming framework and I need to be able to execute some string representing complete python programs. I'm using Python 2.7. I have a config class in which the

Solution 1:

eval("function_name")(arg1, arg2)

or if you have a list of arguments:

arguments= [arg1,arg2,arg3,something]
eval("function_name")(*arguments)

Solution 2:

You have three options, roughly speaking. You can keep going with eval(),you could actually write the string as a file and execute it with subprocess.Popen(), or you could call the function something besides main() and call it after defining it with eval().

exec() way:

In the string you want to exec

main(#REPLACE_THIS#)

Function to evaluate

import string
defexec_with_args(exec_string,args):
    arg_string=reduce(lambda x,y:x+','+y,args)
    exec_string.replace("#REPLACE_THIS#", arg_string)

Subprocess way:

import subprocess
 #Write string to a file
 exec_file=open("file_to_execute","w")
 exec_file.write(string_to_execute)
 #Run the python file as a separate process
 output=subprocess.Popen(["python","file_to_execute"].extend(argument_list),
     stdout=subprocess.PIPE)

Function Definition Way

In the string you want to exec

deffunction_name(*args):
    import sys

    defa(x,y):
        return x

    defb(y):
        return y

    definner_main(x,y):
        lambda x,y: a(b(y),a(x,y))

    inner_main(*args)

Outer code

exec(program_string)
function_name(*args)

Post a Comment for "Passing Arguments To Python Eval()"