使用eval设计计算器的利弊 [英] Pros and Cons on designing a calculator with eval

查看:109
本文介绍了使用eval设计计算器的利弊的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用kivy为android制作一个计算器,并且几乎完成了(不能使用java,因为python是我所知道的唯一语言)。它的工作方式是,用户输入一个表达式,然后使用eval评估该表达式。目前,在我的应用中,评估表达式可以包含数字,数学运算符(+,-,/,*)以及数学模块中的大多数运算符(简而言之,这是一种科学计算器),并且可以按预期运行。将来,我计划集成matplotlib以向应用程序添加图形功能。因此,在上下文中,评估是一个安全的选择。鉴于我在编程方面的经验有限,在很多情况下我都不认为eval是一种不安全的方法,就在几天前,我偶然发现了一个讨论与eval相关的安全性问题的线程。

I'm making a calculator for android using kivy and it's almost done (cannot use java becasue python is the only language I know). The way it works is, the user inputs an expression and eval is used to evaluate that expressions. At the moment, in my app, the eval expression can contain numbers, mathematical operators (+, -, /, *) and most of the operators from math module (In short, it's a scientific calculator) and it works as intended. In future I'm planning on integrating matplotlib to add graphical capabilities to the app. So within the context, is eval a safe option. Given my limited experience in programming I didn't think of eval as being an unsafe method in a lot of situations, it was just a few days ago when I stumbled upon a thread which discussed the safety issues associated with using eval.

那么将评估值更改为我的应用程序中的其他内容还是更好?在给定情况下安全吗?如果对前者是肯定的,那么最好的选择是什么,而无需过多更改我的代码。同样最好是在python标准库中,这样我就不会增加应用程序的大小)

So is it better to change the eval to something else within my app or is it safe in the given situation? if yes to the former, what's the best alternative without changing my code too much. Also it'd be better if it is in the python standard library so that I don't increase the app size)

编辑:顺便说一句,eval表达式是在实时(不确定是否重要)。

Btw, the eval expression is calculated in real time (not sure if this matters).

推荐答案

这篇文章应该对您有用-几乎恰是您要执行的操作。

This article ought to be of good use to you -- it's almost precisely what you're trying to do.

另一方面,是一个很好的警告,说明可能发生的情况如果您不小心的话。大概有很好的方法(也许只是过滤掉所有包含双下划线的输入,作为一个非常简单的开始),但是值得记住的是Python有很多魔术,并且大多数所说的魔术可以通过<$ c $访问。 c> eval()。

This one, on the other hand, is a good warning as to what could happen if you're not careful. Presumably there are good ways around this (maybe just filter out any input containing double underscores, as a really really simple start), but it's worth remembering that Python has lots of magic, and that most of said magic is accessible through eval().

这篇关于使用eval设计计算器的利弊的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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