在python中,一般都是使用eval,不过这个表达式不够安全。今天在stackoverflow上看到有人说ast这个模块
查了一下
ast.literal_eval(node_or_string)
Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.
This can be used for safely evaluating strings containing Python expressions from untrusted sources without the need to parse the values oneself.可以实现安全的代码转换,使用起来很简单
import ast
userAnser = ast.literal_eval([1,2,3,4])
本文介绍了一种使用Python的ast模块安全地评估表达式的方法。通过ast.literal_eval函数,可以从不可信源安全地评估包含Python表达式的字符串,避免了直接使用eval函数的安全风险。这种方法仅允许评估字符串、数字、元组、列表、字典、布尔值和None等基本的数据结构。
1374

被折叠的 条评论
为什么被折叠?



