python - 如何在 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()
?
解决方案
推荐阅读
- azure - 是否有为发送到 Azure IoT 中心的 D2C 遥测数据启用压缩的选项?
- javascript - 删除 Mac .app 文件在 Chrome 中无法正常工作,而在 Safari 中正常工作
- amazon-web-services - 为什么我的 IAM 策略没有使用 terraform 附加到我的 IAM 角色?
- node.js - 为什么我无法让我的后端文件 server.js 连接到前端?错误:POST http://localhost:3000/api/person/add 400(错误请求)?
- c - SIGUSR1 信号未触发
- python - 如何使用 Tensorflow 将固定大小的输入变压器转换为可变固定输入变压器?
- python - 从评论列中提取句子并将其添加到新列中,为每个新句子重复其他行
- visual-studio-code - 如何更改特定语言的评论样式
- coq - 在 Coq 中使用 Program 定义时,Obligations 中缺少信息的问题
- python - 熊猫有没有办法根据一列中的数量对数据框中的行进行分组?