I am working in the Google Application Engine environment where I am loading doctests and python code from strings to test Python homework assignments. My basic implementation (Provided by Alex Martelli) appears to work for all of my problems except for those containing the print statement. Something seems to go wrong when I attempt to execute the print command within GAE.
How would you modify this example to capture anything written out by the print statement?
#This and most other code works
class X(object): pass
x=X()
exec 'a=23' in vars(x)
#This throws an error.
class X(object): pass
x=X()
exec 'print 23' in vars(x)
I think Hooked has the right answer, but I think you'd be better off storing the value of
sys.stdout
before you modify it and restoring that value afterwards rather than restoringsys.__stdout__
because (I think) the App Engine runtime tinkers withsys.stdout
in its own way.That leaves you with something like
For this problem I like to capture the string output directly. Inside your function I would use something like:
And finish with:
# restore stdout and stderr
sys.stdout = sys.__stdout__
To restore normal the function of print.