我试图构建一个解析字符串的python类,如果它匹配的正则表达式看起来像一个函数调用尝试调用该函数的正则表达式 类,传入任何参数。如何将(多个)正则表达式解析函数参数传递给一个python函数
例如像 “富(” A”,20 “)的字符串” 会转化成类似self.foo( “A”,20)。
这里是我到目前为止的代码。 。
class FooTranslate(object):
def create_string(self, letter, size):
return letter*size
def run_function(self, func_str):
match = re.match("([\w_]+)\((|[\W\d\w\,]+)\)", func_str)
if match == None:
print "Couldn't match a regex!"
return False
else:
func, fargs = match.groups()
try:
if fargs == "":
return self.__getattribute__(func)()
else:
return self.__getattribute__(func)(eval(fargs))
except AttributeError, e:
print "Invalid function call: %s" % (func)
return False
此代码工作的基本情况......
In [1018]: foot = FooTranslate()
In [1019]: foot.run_function("foo()")
Foo!
In [1020]: foot.run_function("bar(2)")
FooFoo
使用2级参数的函数的情况下
但是:
In [1021]: foot.run_function("create_string('a', 2)")
in run_function(self, func_str)
24 return self.__getattribute__(func)()
25 else:
---> 26 return self.__getattribute__(func)(eval(fargs))
27 except AttributeError, e:
28 print "Invalid function call: %s" % (func)
TypeError: create_string() takes exactly 3 arguments (2 given)
eval()调用返回fargs作为元组的原因是create_string() 仅将一个参数作为参数。任何想法如何我可以通过一个函数调用传递可变数量的参数 ?或者有更好的替代方法来做到这一点?
看一看'ast.literal_eval()'作为一个更安全的替代EVAL。 – Duncan