How to execute a file outside module's namespace?

Slawomir Nowaczyk slawomir.nowaczyk.847 at student.lu.se
Thu Aug 10 06:43:53 EDT 2006


Hello,

Let's say I have a module "emacs", defining function eexecfile(file):

def eexecfile(file):
    # do other stuff
    execfile(file,globals())
    # do other stuff

Now, assume I have file test.py containing an assignment "x=1"

If I run python and do:

import emacs
emacs.eexecfile("test.py")
print emacs.x   # works, x was put in module namespace
print x         # doesn't work, x is not defined in main script namespace

What is the best way to make "print x" work? Using the following:

import __main__
def eexecfile(file):
    # do other stuff
    execfile(file, __main__.__dict__)
    # do other stuff

seems to work, but it gives me a slightly uneasy feeling. Is this the
right way?

-- 
 Best wishes,
   Slawomir Nowaczyk
     ( Slawomir.Nowaczyk at cs.lth.se )

Today advance is so rapid that even the astronauts who set foot on the
moon in 1969 had never seen a digital watch




More information about the Python-list mailing list