Indentation and grouping proposal

Michael P. Reilly arcege at shore.net
Tue Jun 8 11:57:22 EDT 1999


Emile van Sebille <emile at fenx.com> wrote:
: Re: One Liners:

:>>> def myexec(b):
: ...  for stmnt in string.split(b,'\n'):
: ...   exec(stmnt)
: ...
:>>> b="if a: print 'Spam!';print 'Spam2!';\nprint'Yum!'"
:>>> myexec(b)
: Yum!
:>>> a=1
:>>> myexec(b)
: Spam!
: Spam2!
: Yum!
:>>>

Unfortunately, this doesn't work in other namespaces and frames,  but
the following does.

$ cat fexec.py
def myexec(stmts):
  import string, sys
  try:
    raise SystemError
  except SystemError:
    tb = sys.exc_info()[-1]
  f = tb.tb_frame.f_back
  g, l = f.f_globals, f.f_locals
  del tb, f
  for stmt in string.splitfields(stmts, '\n'):
    exec stmt in g, l

$ cat foo.py
import fexec

def foo(x):
  fexec.myexec('print x')
foo(10)

$ python foo.py
10
$

The trick is to get locals and globals of myexec's caller (which could
be in another module).  But, do we know how safe this is? ;)

  -Arcege





More information about the Python-list mailing list