How to safely use exec() in Python?

后端 未结 2 934
甜味超标
甜味超标 2021-01-03 02:06

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

相关标签:
2条回答
  • 2021-01-03 02:50

    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"]
    
    0 讨论(0)
  • 2021-01-03 02:54

    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.

    0 讨论(0)
提交回复
热议问题