Evaluating the contents of a string

Carey Evans careye at spamcop.net
Thu Mar 22 05:06:38 EST 2001


"Matt Barnett" <mbarnett at ualberta.ca> writes:

> In article <snitl5r6oy.fsf at motorola.com>, Aaron Ginn 
> <aaron.ginn at motorola.com> wrote:

> > Is there a simple way to evaluate the contents of a string assuming
> > that string contains only nunbers and mathematical operators?

[...]

> eval("1.1 * 1.15")

You can do that more safely, by passing in a globals() argument:

>>> eval('1.1 * 1.15', {'__builtins__': {}})
1.2649999999999999

Without this (or checking the string's syntax), something like this is
possible (don't try this at home):

>>> eval(r'__import__("os").system(r"echo I\'m so worried | mail root")')
0
>>> eval(r'__import__("os").system(r"echo I\'m so worried | mail root")',
...   {'__builtins__': {}})
Traceback (innermost last):
  File "<stdin>", line 2, in ?
  File "<string>", line 0, in ?
NameError: __import__

You could allow just mathematical operations, too:

>>> import math
>>> gl = {'__builtins__': {}}
>>> for k in dir(math):
...   if k[0] != '_':
...     gl[k] = getattr(math, k)
...
>>> eval('cos(2 * pi)', gl)
1.0

More advanced forms of this are handled by the rexec and Bastion
modules.

If this goes beyond what Aaron wants, I'm sure there's someone out
there that found it interesting.

-- 
	 Carey Evans  http://home.clear.net.nz/pages/c.evans/

	    "Quiet, you'll miss the humorous conclusion."



More information about the Python-list mailing list