how can I use exec with main module globals?

Gabriel Genellina gagsl-py2 at
Tue Jul 15 07:25:29 CEST 2008

En Sat, 12 Jul 2008 16:15:36 -0300, Akathorn Greyhat <akathorn at>  

> Hello, this is my first message in the group.


> I'm spanish so my english sometimes is really bad, sorry =(
> I have a problem and I hope someone has the answer.
> I'm trying to make an in-game python idle, it works great but the exec
> statement can't access the main module globals but only the ones that are
> inside the module in wich I defined the function.
>     def execute(self, string):
>         exec(string, globals(), globals())
> I realized that if I move the code to the main module, It works, but I  
> want
> it to be inside another script.

You have to pass in the namespace of the desired module - instead of  
globals. I'd use an explicit argument:

def execute(self, string, namespace):
     # exec string in namespace # 2.5
     exec(string, namespace) # 3.0

Use it this way:

execute("a=1", target_module.__dict__)

then target_module.a will be 1

Gabriel Genellina

More information about the Python-list mailing list