interactive execution

Jive Dadson jdadson at yahoo.com
Tue Feb 8 22:23:56 EST 2005



Jeff Shannon wrote:
> 
> Jive Dadson wrote:
> 
> > How does one execute arbitrary text as code within a module's context?
> >
> > 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.
> 
> You can do
> 
>     exec codestring in globaldict, localdict
> 
> (Or something like that, this is from unused memory and is untested.)
>   The net effect is that exec uses the subsequent dictionaries as its
> globals and locals, reading from and writing to them as necessary.
> 
> (Note that this doesn't get you any real security, because malicious
> code can still get to __builtins__ from almost any object...)
> 
> Jeff Shannon
> Technician/Programmer
> Credit International

Promising, but,

Traceback (most recent call last):
  File "F:/C++ Projects/zardude/temp.py", line 9, in -toplevel-
    exec "foo = 555" in globaldict, localdict
NameError: name 'globaldict' is not defined



More information about the Python-list mailing list