Catching results of an exec

dsavitsk dsavitsk at e-coli.net
Thu Sep 19 04:54:47 CEST 2002


>>> class foo:
...     def do_it(self, arg):
...         exec(arg)
...     def get_it(self, arg):
...         return eval(arg)

>>> f = foo()
>>> f.do_it('self.a = "bar"')
>>> b = f.get_it('self.a')
bar

is this too simple?

-d


"Greg Fortune" <lists at gregfortune.com> wrote in message
news:3d88f701$0$304$39cecf19 at nnrp1.twtelecom.net...
> Is there any way to "catch" the value produced by an exec?  I'm
considering
> things like print statements that don't really assign a value, but do send
> a result to stdout.
>
> For example, if I execute
>
> exec('print dir()')
>
> from an interpreter, there will be some stuff spit out on the console.
> What if I really wanted to display the list from dir() in a different way?
> I'm working on a really dinky server that will sit on a machine and
execute
> arbitrary python code.  I want the results from the code execution to be
> returned to client.
>
> Even just eval('dir()') exhibits the desired behavior, but only from an
> interactive interpreter.
>
> Right now I've got a nasty hack that redirects stdout, uses an
> InteractiveInterpereter from the code module to execute the code, writes
to
> an output file, reads the result from the file, restores stdout and then
> sends the result to the client.  Hopefully, that's a terrible way to do
it.
>  It just occured to me that I can probably use a pipe in place of the
> output file, but still....
>
> It would be great if exec and eval set something somewhere that held the
> results of the code execution.  I looked in the InteractiveInterpreter
> (which, at least, kicks the results of the code execution out to stdout),
> but all it does is
>
> exec code in self.locals
>
> Did I miss something?
>
> Greg Fortune





More information about the Python-list mailing list