我在 python 中创建了一个函数来通过
exec()
执行通用脚本。它工作得很好,但它在全球范围内创建了功能。我需要在本地创建它们并运行它们,然后我需要删除它们。
我的示例脚本:
def demo_handler(request):
...
return None
我的执行器功能是:
def execute(body: ExecutorCommand):
try:
exec(body.script, globals())
result = demo_handler(body.request)
return {"success": True, "data": result}
except Exception as ex:
return {"success": False, "error": {"type": type(ex).__name__, "message": repr(ex)}}
当我发送带有脚本的第一个请求时,它按预期工作。这样,即使我不发送脚本,我也可以访问之前执行的函数。但我不想要它。有没有办法删除以前执行的功能?
解决方式如下:
def execute(body: Command):
fun_name = _generate_unique_function_name()
try:
# handler() function will come from handler_script
handler_script = body.handler_script.replace("state_handler", fun_name)
exec(handler_script, globals())
...
result = globals()[fun_name](**params)
return {"success": True, "data": result}
except Exception as ex:
logging.error("Unexpected exception on execute command: %s", repr(ex))
return {"success": False, "error": {"type": type(ex).__name__, "message": repr(ex)}}
finally:
if fun_name in globals():
del globals()[fun_name]
else:
return {"success": False, "error": {"type": "Unknown Function", "message": "Couldn't found handler function in script"}}
def _generate_unique_function_name():
return "handler_" + str(uuid.uuid4()).replace("-", "_")