[英]How to pass (multiple) regex parsed function parameters to a python function
I'm trying to build a python class that parses a string and if it matches a regex that looks like a function call attempt to call that function on the class, passing in any parameters. 我正在尝试构建一个解析字符串的python类,如果它与看起来像函数调用的正则表达式匹配,则尝试在类上调用该函数,并传入任何参数。
For example a string like "foo("a", 20")" would translate to something like self.foo("a", 20). 例如,像“ foo(” a“,20”)“这样的字符串将转换为类似self.foo(” a“,20)的东西。
Here is the code that I have so far.. 这是我到目前为止的代码。
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
This code works in the basic cases... 此代码在基本情况下适用...
In [1018]: foot = FooTranslate()
In [1019]: foot.run_function("foo()")
Foo!
In [1020]: foot.run_function("bar(2)")
FooFoo
However in the case of using 2 argument functions: 但是,在使用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)
The reason why is that the eval() call returns fargs as a tuple, which create_string() takes as only a single argument. 原因是eval()调用将fargs作为元组返回,create_string()仅作为单个参数。 Any idea how I can pass a variable number of arguments through to a function call?
知道如何将可变数量的参数传递给函数调用吗? Or have a better alternative way to do this?
还是有更好的替代方法来做到这一点?
You can use the *
operator to explode a tuple into separate arguments to a function. 您可以使用
*
运算符将元组分解为函数的单独参数。 For example: 例如:
def f(a, b, c):
print a, b, c
If I call f(...)
like this: 如果我这样调用
f(...)
:
f((1,2,3))
I get an error: 我收到一个错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: f() takes exactly 3 arguments (1 given)
But if I call it like this: 但是,如果我这样称呼它:
f(*(1,2,3))
I get: 我得到:
1 2 3
The *
operator will even work if the function takes a variable number of arguments. 如果函数采用可变数量的参数,则
*
运算符甚至可以工作。 For example, given the following function: 例如,给定以下功能:
def f2(a, b, *args):
print a, b,
for x in args:
print x,
print
If I call f2(*(1,2,3,4,5))
it prints: 如果我调用
f2(*(1,2,3,4,5))
它会打印:
1 2 3 4 5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.