I have been tasked with building an application where an end user can have custom rules to evaluate whether a returned query results in a warning or alert (based on there ow
Your exec
statement isn't adding retVal to your local environment, but to the safe_dict
dictionary. So you can get it back from there:
execCd = """
if (abs(22.0) >= abs(-162.0)):
retVal = 22.0
else:
retVal = -162.0
"""
safe_list = ['math','acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'de grees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']
safe_dict = dict([ (k, locals().get(k, None)) for k in safe_list ])
safe_dict['abs'] = abs
exec(execCd,{"__builtins__":None},safe_dict)
retVal = safe_dict["retVal"]
The only safe way to use eval
or exec
is not to use them.
You do not need to use exec. Instead of building a string to execute, parse it into objects, and use that to drive your code execution.
At its simplest, you can store functions in a dict, and use a string to select the function to call. If you're using python syntax, python provides all the utilities to parse itself, and you should use those.