eval vs. exec

Just just at xs4all.nl
Mon May 27 15:26:34 EDT 2002


In article <3cf27f1e at si-nic.hrz.uni-siegen.de>,
 Simon Budig <Simon.Budig at unix-ag.org> wrote:

> Whow, this is impressive. Yes, this seems to work although this is
> way beyond my python-scope  :-)

It's defintely pretty cool, the way Michael handled this...

> I am not sure if I want to do this or if the interception of
> sys.stdout is a more - uhm - Simon-friendly solution...    ;-)

Here's another solution:

import sys, __builtin__

class NullFile:
   def write(self, s):
      pass

def super_eval(expr):
   code = compile(expr, "", "single")
   try:
      del __builtin__._
   except AttributeError:
      pass
   savestdout = sys.stdout
   try:
      sys.stdout = NullFile()
      eval(code)
   finally:
      sys.stdout = savestdout
   return getattr(__builtin__, "_", None)


>>> super_eval("a = 2")
>>> super_eval("3*4")
12
>>> super_eval("a = 2; b = 3; a*b")
6
>>> 


Just



More information about the Python-list mailing list