How does rexec work?

Gordon McMillan gmcm at hypernet.com
Wed Nov 3 22:03:21 EST 1999


John Farrell writes:

> I'm confused about rexec and how it works. 

Aren't we all.

> 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.

It doesn't. "renv1.r_exec('import string')" binds the module 
string to the name "string" in renv1's __main__. __main__ is a 
mutable object, stored in renv1.modules. So it's available to 
your "renv1.r_eval(...)".

Looks like renv1.modules plays the same role here that 
sys.modules plays normally. That is, if a module has been 
imported somewhere, it's in sys.modules. You still need to 
import it in other modules, but those imports are nearly free.

>  (b) Why doesn't r_import work like r_exec('import ...')? What's
>  it
> supposed to do then?

r_import is like __import__, not like the keyword import. It 
returns the module.

    mod = renv2.r_import('string')
    renv2.modules['__main__'].string = mod

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

That'll teach you to dive in the deep end!

- Gordon




More information about the Python-list mailing list