首页 > 解决方案 > 如何在 python 3.7 中使用 eval() 和 compile()?

问题描述

我想评估 Python 3.7 中的表达式,该表达式从配置文件中读取为字符串。该应用程序是一个数据记录器,用户应该能够在配置文件中定义他自己的原始 ADC 值的转换。使用eval()andcompile()很方便,但被认为是不安全的。我尝试使用ast.literal_eval(),但它不适用于 Python 3.7,因为它不允许使用像+-*/. 最后我想出了这样的事情:

def convert(code, value):
    try: 
        return eval(code, {'__builtins__': {}}, {'value': value})
    except RecursionError as e:
        print(str(e))
    except NameError as e:
        print(str(e))

def compile_expression(expr):

    if '__' in expr:  # check for double underscore
        print('expression contains illegal characters')
        return None
    try:
        code = compile(expr, '<String>', 'eval')  # compile it for use with eval
    except SyntaxError as e:
        print('Invalid Syntax in expression. Using default value.')
        code = compile('value', '<String>', 'eval')       
    return code

expr = '(value-1)/0.005'         # string is read from a config file
code = compile_expression(expr)  # compile string 

if code is not None:
    t = convert(code, 1.1) # convert ADC value to temperature
    print(t)

至少我尽量让它安全。有没有人建议如何做得更好或有合适的替代方法eval()and compile()

标签: pythoncompilationevalabstract-syntax-tree

解决方案


推荐阅读