如何获取Python中exec()定义的可调用函数?

问题描述 投票:0回答:1

假设我想要一个函数

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

我想知道这样做的一般和正确方法是什么?

python python-3.x string function exec
1个回答
1
投票

您可以使用

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
© www.soinside.com 2019 - 2024. All rights reserved.