将参数传递给python eval()

时间:2014-01-13 19:56:15

标签: python code-generation eval argument-passing

我正在做基因编程框架,我需要能够执行一些代表完整python程序的字符串。我正在使用Python 2.7。我有一个配置类,其中定义了基元集。让我们说

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

    def b(self,y):
        return y

我正在使用python检查模块提取函数,我想用导入和所有东西创建一些可执行的源代码。我最终得到一个看起来像这样的字符串

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)

我的问题是我不知道如何将命令行参数传递给我使用eval()运行的字符串。 如何将命令行参数传递给我想用eval()运行的源文件?

编辑:有数百万人因此写入文件不是一个很好的选择。

编辑:我犯了一个错误。 eval()方法仅用于表达式而不是语句,因此使用exec()是正确的方法

2 个答案:

答案 0 :(得分:2)

粗略地说,你有三种选择。您可以继续使用eval(),您可以将字符串写为文件并使用subprocess.Popen()执行它,或者您可以调用除main()之外的函数并在定义它之后调用它eval()

exec()方式:

在要执行的字符串

main(#REPLACE_THIS#)

评估功能

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)

子进程方式:

 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)

功能定义方式

在要执行的字符串

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)

外码

exec(program_string)
function_name(*args)

答案 1 :(得分:1)

eval("function_name")(arg1, arg2)

或者如果你有一个参数列表:

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