简体   繁体   English

如何将字符串转换为函数调用?

[英]How to convert string into a function call?

I have a variable with a call to a function in string format.我有一个以字符串格式调用函数的变量。 For example...例如...

val = "add(3,4)"

and the function is功能是

def add(a,b):
     sum =a+b;
     print(sum)

this is received from a file and therefore can't be changed.这是从文件中收到的,因此无法更改。 Is there a way I can convert the string into a format which I can call the function?有没有办法可以将字符串转换为可以调用函数的格式? ie IE

add(3,4)

which would run the add(3,4) function.这将运行add(3,4)函数。

I tried to use globals :我尝试使用globals

s= globals()['add']
s() 

but am unable to pass argument add(3,4) .但我无法传递参数add(3,4) Can any one help me how to pass arguments?任何人都可以帮助我如何传递参数吗?

In case the function arguments are made of literals you can use ast.literal_eval for parsing them:如果函数参数由文字组成,您可以使用ast.literal_eval来解析它们:

import ast

func, args = val[:-1].split('(', 1)
globals()[func](*ast.literal_eval(args))

In order to have better control over what functions the user can trigger it's better to put them into a separate dictionary:为了更好地控制用户可以触发的功能,最好将它们放入单独的字典中:

functions = {'add': add}
...
functions[func](*ast.literal_eval(args))

Otherwise any function from the global namespace could be (ab)used.否则可以(ab)使用来自全局命名空间的任何函数。

You can use eval .您可以使用eval

def add(a,b):
    return a+b
eval('add(3,4)') # 7

You can use eval :您可以使用eval

val = 'add'

def add(value):
    return value

eval(val)(4)

As others have mentioned utilizing eval is bad practice, and your design can probably use some adjustments.正如其他人提到的,使用eval是不好的做法,您的设计可能会进行一些调整。

However, you can add a bit of safety to your code if you perform a check before actually executing the eval() function:但是,如果在实际执行eval()函数之前执行检查,则可以为代码添加一些安全性:

def add(a,b):
    return a + b

func = "add(3,4)"

# Check if the calling function exists in `locals()` dictionary.
if func.split('(', maxsplit=1)[0] in locals():
    print(eval(func))   # Prints 7

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM