从文本文件加载函数参数

时间:2014-07-03 09:27:43

标签: python python-2.7 eval

我有以下功能:

def request( url, type, headers, simulate = False, data = {}):

我希望能够从文本文件加载参数并将它们传递给函数,我尝试使用下面的邪恶评估:

if execute_recovery:
    for command in content:
        logger.debug("Executing: "+command)
        try:
            result = eval(utilities.request("{0}").format(command))

            if not result["Success"]:
                continue_recovery = utilities.query_yes_no("Warning: Previous recovery command failed, attempt to continue recovery?\n")
                if not continue_recovery:
                    break
                else:
                    logger.debug("Command executed successfully...")
         except Exception, e:
             logger.debug( "Recovery: Eval Error, %s" % str(e) )

其中命令是文本文件中的一行,如:

"http://192.168.1.1/accounts/1/users/1",delete,headers,simulate=False,data={}

这会引发以下错误:

'request() takes at least 3 arguments (1 given)'

所以这可能意味着它将命令解释为单个字符串而不是不同的参数。

有人知道如何解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

我无法通过评估或格式了解您尝试做的事情。首先,您已将eval放在request本身的调用周围,因此它将评估返回值,而不是使用某个动态值调用它。

但你根本不需要评估。您只需使用***运算符传递参数:

args = []
kwargs = {}
for arg in command.split(','):
    if '=' in arg:
        k, v = arg.split('=')
        kwargs[k] = ast.literal_eval(v)
    else:
        args.append(arg)
result = utilities.request(*args, **kwargs)

答案 1 :(得分:0)

使用@ BurhanKhalid的建议,我决定将参数存储为json对象,并在运行时加载它们,如下所示:

在此处存储参数:

def request( url, type, headers, simulate = False, data = {}):
    if simulate:
        recovery_command = {"url":url, "type" : type, "data" : data}
        recovery.add_command(json.dumps(recovery_command))
        ...

在此处加载参数:

def recovery():
...
    if execute_recovery:
        for command in content:
            logger.debug("Executing: "+command)
            try:

                recovery_command = json.loads(command)

                result = utilities.request(url = recovery_command["url"], type = recovery_command["type"], headers = headers, simulate = False, data = recovery_command["data"])

                if not result["Success"]:
                    continue_recovery = utilities.query_yes_no("Warning: Previous recovery command failed, attempt to continue recovery?\n")
                    if not continue_recovery:
                        break
                else:
                    logger.debug("Command executed successfully...")
            except Exception, e:
                logger.debug( "Recovery: Eval Error, %s" % str(e) )