Passing arguments to python eval()

给你一囗甜甜゛ 提交于 2021-02-11 06:59:42

问题


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 primitive sets are defined. Lets say

class Foo():
    def a(self,x):
        return x

    def b(self,y):
        return y

I'm extracting the functions with the python inspect module and I want to create some executable source code with imports and everything. I end up with a string that looks like this

import sys

def a(x,y):
    return x

def b(y):
    return y

def main(x,y)
    lambda x,y: a(b(y),a(x,y))

main(*sys.argv)

My problem is that I don't know how to pass command line arguments to the string I'm running with eval(). How can I pass command line arguments to a source file I want to run with eval()?

Edit: There are millions of individuals so writing to a file is not a great option.

Edit: I made a mistake. The eval() method is used only for expressions and not statements so using exec() is the correct approach


回答1:


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
def exec_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

def function_name(*args):
    import sys

    def a(x,y):
        return x

    def b(y):
        return y

    def inner_main(x,y):
        lambda x,y: a(b(y),a(x,y))

    inner_main(*args)

Outer code

exec(program_string)
function_name(*args)



回答2:


eval("function_name")(arg1, arg2)

or if you have a list of arguments:

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


来源:https://stackoverflow.com/questions/21100203/passing-arguments-to-python-eval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!