How does rexec work?

John Farrell jfarrell at mincom.com
Wed Nov 3 18:37:31 EST 1999


I'm confused about rexec and how it works. Consider the following code:
---
import rexec, traceback

renv1 = rexec.RExec()
renv1.r_exec('import string')
print renv1.r_eval("string.upper('This is a test')")

try:
    renv2 = rexec.RExec()
    renv2.r_import('string')
    print renv2.r_eval("string.upper('This is a test')")
except:
    traceback.print_exc()
----
The things I don't understand are:

 (a) In the renv1 example, where does the name string get preserved
to be available in the eval? The relevant code from rexec is included
below, but I don't see how the self.modules dict gets into the
__main__ namespace.
 (b) Why doesn't r_import work like r_exec('import ...')? What's it
supposed to do then?

I guess part of my problem is that I am not 100% familiar with
the Python namespace fiddling stuff yet. Thanks for any help!

John
----
    # Add a module -- return an existing module or create one

    def add_module(self, mname):
        if self.modules.has_key(mname):
            return self.modules[mname]
        self.modules[mname] = m = self.hooks.new_module(mname)
        m.__builtins__ = self.modules['__builtin__']
        return m

    # The r* methods are public interfaces

    def r_exec(self, code):
        m = self.add_module('__main__')
        exec code in m.__dict__

    def r_eval(self, code):
        m = self.add_module('__main__')
        return eval(code, m.__dict__)
----




More information about the Python-list mailing list