getting values from an "exec" statement

Greg Krohn ask at me.com
Tue Sep 30 19:37:58 EDT 2003


"Toby Donaldson" <tjd at sfu.ca> wrote in message
news:ad32251c.0309301513.1b11a8ce at posting.google.com...
> Hi all,
>
> I'm designing an educational application that will run Python code and
> check the output against a pre-define answer. I want to use the "exec"
> statement to run the code, but I don't know how to get output from it.
>
> For instance, exec works like this:
>
> >>> code = """
> for i in xrange(1, 5):
> print i
> """
> >>> exec code
> 1
> 2
> 3
> 4
>
> I want to store the values output by the print statement in a list. Is
> there anyway to re-direct the output of the exec statement?

The code run by exec is run in the same scope as the exec (by default). So
anything done "in" the exec is visible to things "outside" the exec. Like
this:

l = []
code = """for i in xrange(1, 5):
  l.append(i)"""
exec code
print l


greg






More information about the Python-list mailing list