eval vs. exec

Simon Budig Simon.Budig at unix-ag.org
Mon May 27 10:20:52 EDT 2002


Hi.

I currently have problems to let code inside strings execute as I want
to have it. Especially the difference between "eval" and "exec"
(resp. compiling as 'eval' or as 'single') makes me headache.

I want to execute things like the three following strings:

"a = 2"           ---> returns nothing
"3 * 4"           ---> returns 12
"a=2; b=3; a*b"   ---> returns 6

My current code looks like this:

mathenv = {"__builtins__" : {}}

def evalmath (mathstuff):
   global mathenv
   mathenv['__builtins__'] = {}
   code = None
   try:
      code = compile (mathstuff, "", 'eval')
   except:
      try:
         code = compile (mathstuff, "", 'single')
      except:
         return "Error, was unable to compile the code"
         # actually there is some exception stuff in here.
   if code:
      try:
         result = eval (code, mathenv)
      except:
         result = "Error, unable to evaluate the code."
         # actually there is some exception stuff in here.
      return result
      

the tests result in:

>>> print "result:", evalmath("a = 2")
result: None
>>> print "result:", evalmath("3 * 4")
result: 12
>>> print "result:", evalmath("a=2; b=3; a*b")
result:
6
None

While the first two things are OK, the last one is not, since the
evaluated result gets printed instead of returned. The other problem
is that the code written above is quite ugly and looks like a hack.
For the latter problem there surely is a workaround by reassigning
sys.stdout or something like this, but this is really evil.

Is there a more pythonic way to do this?

Thanks,
        Simon

-- 
      Simon.Budig at unix-ag.org       http://www.home.unix-ag.org/simon/



More information about the Python-list mailing list