Assigning output from a simple python statement
William Park
parkw at better.net
Thu Mar 16 15:18:35 EST 2000
On Thu, Mar 16, 2000 at 07:14:57AM +0000, 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'm fairly new to python and the best I can come up with is:
>
> # Assume the statement is stored in a dictionary with the key "code".
>
> from os import popen
>
> cmdDict['code'] = "print 'Hello World'"
>
> line = popen( "python -c "+`cmdDict['code']` ).readline()
> process( line )
>
> Any gurus out there have better suggestions ?
>
> thanks,
> Wilson Fletcher
Usual solution is 'eval' for expression and 'exec' for statement (see
online doc for details). To capture all output to <stdout>, you can
point 'sys.stdout' to some file, and later restore it to the default
'sys.__stdout__'.
--William
More information about the Python-list
mailing list