Assigning output from a simple python statement
Anthony J Wilkinson
anthony at dstc.edu.au
Thu Mar 16 03:08:35 EST 2000
On 16 Mar 2000, Wilson Fletcher wrote:
> I would like to execute an unknown python statement and store the output.
>
> It will typically be a print statement. eg. "print 'Hello World'"
>
> I won't know the statement until runtime becuase it will come from a
> database. BUT I want to capture anything that goes to stdout and process
> it.
I got the following (slight modifications made) from
<ftp://ftp.python.org/pub/python/mail/hypermail/python-recent/0759.html>
after a quick search on <http://www.python.org/search/> for 'redirect
stdout'
>>> import sys
>>> class Output:
... def __init__(self):
... self.text=""
... def write(self, string):
... self.text = self.text + string
... def writelines(self, lines):
... for lin in lines: self.write(line)
... def close(self):
... pass
... def flush(self):
... pass
... def isatty(self):
... return 0
...
>>> cmdstr = "print 'Hello World'"
>>> oldstdout=sys.stdout
>>> sys.stdout=Output()
>>> exec cmdstr
>>> # Note I left the brackets off this time but I'm sure someone can
... # nitpick something else :-)
...
>>> result = sys.stdout.text
>>> sys.stdout = oldstdout
>>> print result
Hello World
Regards,
Anthony
_____________________________________________________________________
Anthony J Wilkinson anthony at dstc.com
Software Engineer http://dstc.com
DSTC Pty Ltd Ph: +61 7 3365 4310
More information about the Python-list
mailing list