How to capture stdout in an exec'ed string?

Jeff jam at quark.emich.edu
Wed Nov 24 13:32:34 CET 1999


On Wed, Nov 17, 1999 at 09:44:11PM +0000, Preston Landers wrote:
> Hello all.
[..snipped..]
> 
> At no time do I want the old program's output to be visible to the
> user.  Therefore I must find some way trap the print statements.
> (Going through the old code and changing all the prints to a custom
> function call is not really an option at this point.)
> 
> In the subject line of this msg I said an "exec'ed statement" but it
> not really need be.  I can just instantiate the old program and call
> the methods I need.  Something like this:
> 
> try:
>    cruft = my_ancient_class()
>    cruft.__stdout__ == My_STDOUT()
>    cruft.do_your_thang()
> except SystemExit, msg:
>    process(msg)
> 
> I guess my question is how to accomplish the 3rd line of my code.  What
> kind of class does My_STDOUT() need to be?  Something mimicing a file
> handle?  How to actually "attach" it?  My guess is that I will have to
> eval my_ancient_class in a special namespace?
> 

how about just calling 'open' and assigning it to 'sys.stdout'? your
assumption is correct-- stdout is nothing more than a standard file handle
(under UNIX anyway).

you could try something like this (untested):

sys.stdout = open("/dev/null", "w")
cruft = my_ancient_class()
try:
 cruft.do_your_thang()
except SystemExit, msg:
 process(msg)

you may also want to keep track of the 'old' stdout file handle so it can be
restored later.

hope that helps.

regards,
J
-- 
|| visit gfd <http://quark.emich.edu/>
|| psa member #293 <http://www.python.org/> 
|| New Image Systems & Services, Inc. <http://www.newimage.com/>




More information about the Python-list mailing list