[Tutor] RExec woes [Capturing rexec's output]

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Wed, 24 Oct 2001 23:09:10 -0700 (PDT)


On Wed, 24 Oct 2001, Danny Yoo wrote:

> On Tue, 23 Oct 2001, Scott Moynes wrote:
> 
> > As a quick example, here's approximately what I'm trying to
> > accomplish:
> > 
> > >>> r=rexec.RExec()
> > >>> m=r.add_module('sys')
> > >>> s=StringIO.StringIO()
> > >>> m.__dict__['stdin']=s
> > >>> r.r_exec('print "something"')
> > something
> > >>> s.getvalue()
> > ''
> 
> Quick solution:
> 
> ###
> import rexec, StringIO
> r = rexec.RExec()
> r.make_delegate_files()
> s = StringIO.StringIO()
> r.restricted_stdout = s
> r.s_exec("import sys")
> r.s_exec("sys.stdout.write('hello world')")
> ###


Oh, by the way, this also works with the regular "print" statement:

###
import rexec
import StringIO
r = rexec.RExec()
r.make_delegate_files()            ## A mystery to me why this isn't
                                   ## documented better... *sigh*
s = StringIO.StringIO()
r.restricted_stdout = s
r.s_exec("print 'hello world'")
print "Here's what we captured: ", s.getvalue()
###

Sorry about complicating matters...