Creating a calculator

Pierre-Alain Dorange pdorange at pas-de-pub-merci.mac.com
Fri Jul 1 09:03:19 EDT 2016


Chris Warrick <kwpolska at gmail.com> wrote:

> > More reduced :
> > ----------------------------------
> > u=raw_input('Enter calculation:")
> > print eval(u)
> > ----------------------------------
> > works and compute :
> > 1+2+3+4-1+4*2
> > 2+3.0/2-0.5
> >
> > Perform better and shorter, but less educationnal of course...
> 
> No, this is awful. It's a great way to compromise your system's
> security. Never use eval() for any reason, especially with user input
> — if you were to type in __import__('os').system('…') with some
> particularly dangerous command (rm, format, …), you would kill your
> system.

Yes you're right, eval can be really dangerous.
You could make it (a little) safer using env ; but a hacker could always
break things with eval.

-------------------------------------
env={}
env["__builtins__"] = None

u=raw_input('Enter calculation:")
print eval(u,env)
-------------------------------------

-- 
Pierre-Alain Dorange               Moof <http://clarus.chez-alice.fr/>

Ce message est sous licence Creative Commons "by-nc-sa-2.0"
<http://creativecommons.org/licenses/by-nc-sa/2.0/fr/>



More information about the Python-list mailing list