mybot/common/handle_eval_data.py

30 lines
1005 B
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

def eval_data(data):
"""
执行一个字符串表达式,并返回其表达式的值
"""
try:
if hasattr(eval(data), "__call__"):
return data
else:
return eval(data)
except Exception:
return data
def eval_data_process(data):
"""
将数据中的字符串表达式处理后更新其值为表达式
"""
# 如果目标数据是字符串直接尝试eval
if isinstance(data, str):
return eval_data(data)
# 如果目标数据是列表遍历列表的每一个数据再用递归的方法处理每一个item
elif isinstance(data, list):
for index, item in enumerate(data):
data[index] = eval_data_process(eval_data(item))
# 如果目标数据是字典遍历字典的每一个值再用递归的方法处理每一个value
elif isinstance(data, dict):
for key, value in data.items():
data[key] = eval_data_process(eval_data(value))
return data