interactive execution

George Yoshida ml at dynkin.com
Tue Feb 8 21:38:45 EST 2005


Jive Dadson wrote:

> I've got some code that compiles some text and then executes it.  When
> the string is "print 'Hello'", it prints "Hello".  I get no exception
> when I compile and execute "foo = 555".  If I then compile and exec
> "print foo", I get a name error. The variable foo is undefined. My
> assumption is that the "exec" command created a new namespace, put "foo"
> in that namespace, and then threw the namespace away.  Or something.
> 
> I know it must be possible to do this, because it's exactly what
> programs like IDLE do.
> 

   exec statement in name_space
will do the trick.

 >>> d = {}
 >>> exec 'foo=555' in d
 >>> d['foo']
555
 >>> exec "print foo" in d
555

- george



More information about the Python-list mailing list