将参数传递给python eval() [英] Passing arguments to python eval()

查看:96
本文介绍了将参数传递给python eval()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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)

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

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()?

编辑:有数以百万计的个人,因此写入文件不是一个好选择.

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

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

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

推荐答案

粗略地说,您有三个选择.您可以继续使用 eval(),实际上可以将字符串写为文件并通过 subprocess.Popen()执行它,也可以在函数之外调用其他函数 main(),并在使用 eval()定义它之后调用它.

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().

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)

这篇关于将参数传递给python eval()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆