interactive execution
Jeff Shannon
jeff at ccvcorp.com
Wed Feb 9 12:36:55 EST 2005
Jive Dadson wrote:
> Yeah. I got it.
>
> exec "foo = 555" in globals(), locals() does the trick.
You can do it with your own dicts, too -- but they must already exist,
exec doesn't create them out of nowhere.
>>> myglobals = {'a':2, 'b':5}
>>> mylocals = {'c': 3}
>>> exec "d = a * b + c" in myglobals, mylocals
>>> myglobals
{'a': 2, '__builtins__': {...}, 'b': 5}
>>> mylocals
{'c': 3, 'd': 13}
>>>
This gives you some control over what the exec'ed statement actually
sees, as well as what happens with the results. (But as I mentioned
before, there is no real security here if you're exec'ing arbitrary
code -- there's no sandboxing involved, and the exec'ed string *can*
use that __builtins__ reference (among other things) to do all sorts
of malicious stuff.)
Jeff Shannon
Technician/Programmer
Credit International
More information about the Python-list
mailing list