使用 python 的 eval() 与 ast.literal_eval() [英] Using python's eval() vs. ast.literal_eval()

查看:27
本文介绍了使用 python 的 eval() 与 ast.literal_eval()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一些代码的情况,其中 eval() 作为可能的解决方案出现.现在我以前从来没有使用过 eval() 但是,我遇到了很多关于它可能导致的潜在危险的信息.也就是说,我对使用它非常谨慎.

I have a situation with some code where eval() came up as a possible solution. Now I have never had to use eval() before but, I have come across plenty of information about the potential danger it can cause. That said, I'm very wary about using it.

我的情况是我有用户提供的输入:

My situation is that I have input being given by a user:

datamap = input('Provide some data here: ')

其中 datamap 需要是字典.我四处搜索,发现 eval() 可以解决这个问题.我认为我可以在尝试使用数据之前检查输入的类型,这将是一种可行的安全预防措施.

Where datamap needs to be a dictionary. I searched around and found that eval() could work this out. I thought that I might be able to check the type of the input before trying to use the data and that would be a viable security precaution.

datamap = eval(input('Provide some data here: ')
if not isinstance(datamap, dict):
    return

我通读了文档,但我仍然不清楚这是否安全.eval 是在输入数据后立即评估数据还是在调用 datamap 变量后评估数据?

I read through the docs and I am still unclear if this would be safe or not. Does eval evaluate the data as soon as its entered or after the datamap variable is called?

ast 模块的 .literal_eval() 是唯一安全的选择吗?

Is the ast module's .literal_eval() the only safe option?

推荐答案

datamap = eval(input('Provide some data here: ')) 表示您实际上在之前评估代码 你认为它不安全.一旦函数被调用,它就会评估代码.另请参阅eval 的危险.

datamap = eval(input('Provide some data here: ')) means that you actually evaluate the code before you deem it to be unsafe or not. It evaluates the code as soon as the function is called. See also the dangers of eval.

ast.literal_eval如果输入不是有效的 Python 数据类型,则会引发异常,因此如果不是,则不会执行代码.

ast.literal_eval raises an exception if the input isn't a valid Python datatype, so the code won't be executed if it's not.

在需要时使用 ast.literal_eval eval.您通常不应该评估文字 Python 语句.

Use ast.literal_eval whenever you need eval. You shouldn't usually evaluate literal Python statements.

这篇关于使用 python 的 eval() 与 ast.literal_eval()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆