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

查看:143
本文介绍了使用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 = raw_input('Provide some data here: ')

数据映射需要作为字典的位置。我四处搜寻,发现 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(raw_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(raw_input('在此处提供一些数据:'))表示您实际上在评估代码之前为不安全或不会,它会在调用函数后立即评估代码。另请参见 <$ c $的危险c> eval

datamap = eval(raw_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 >评估。通常,您不应该评估文字的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天全站免登陆