How to capture stdout in an exec'ed string?

Jeff jam at
Wed Nov 24 13:32:34 CET 1999

On Wed, Nov 17, 1999 at 09:44:11PM +0000, Preston Landers wrote:
> Hello all.
> 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()
except SystemExit, msg:

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

hope that helps.

|| visit gfd <>
|| psa member #293 <> 
|| New Image Systems & Services, Inc. <>

More information about the Python-list mailing list