假设我想要一个函数
exec_myfunc
,它可以执行任何输入值为10的用户定义函数。用户应该通过字符串来定义该函数,如下所示:
func1_str = """
def myfunc1(x):
return x
"""
func2_str = """
def myfunc2(x):
return x**2
"""
现在我使用的是一种非常hacky的方式,通过使用正则表达式提取
def
和(
之间的函数名称,如下所示:
def exec_myfunc(func_str: str):
import re
exec(func_str)
myfunc_str = re.search(r'def(.*)\(', func_str).group(1).strip()
return eval(myfunc_str)(10)
print(exec_myfunc(func1_str))
# 10
print(exec_myfunc(func2_str))
# 100
我想知道这样做的一般和正确方法是什么?
ast
模块来解析Python字符串,然后找到函数名称:
import ast
func1 = """
def myfunc1(x):
return x
"""
parsed_func = ast.parse(func1)
for node in ast.walk(parsed_func):
if isinstance(node, ast.FunctionDef):
function_name = node.name
break
print("Function name:", function_name)
打印:
Function name: myfunc1