问题
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.
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)
Edit: Btw, the eval expression is calculated in real time (not sure if this matters).
回答1:
This article ought to be of good use to you -- it's almost precisely what you're trying to do.
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().
来源:https://stackoverflow.com/questions/14515472/pros-and-cons-on-designing-a-calculator-with-eval