My first attempt at subclassing....Gahh!

Alex Martelli aleaxit at yahoo.com
Tue Sep 14 17:01:21 EDT 2004


John Lenton <john at grulic.org.ar> wrote:
   ...
> > save_stdout = sys.stdout
> 
> I believe sys.__stdout__ is there for the purpose of not having to
> 'save' sys.stdout in this way.

Hmmm, almost, but not quite.  If you somehow "know" that your sys.stdout
has not been set by some other module, typically a GUI framework, then,
sure, you don't need to copy sys.stdout yourself.  But if you get into
that habit, eventually you WILL get bitten, when you end up interfering
with exactly that kind of "other framework".  Personally, I far prefer
to cultivate the habit of a full-fledged idiom such as:

    redirected_stdout = cStringIO.StringIO()
    save_stdout = sys.stdout
    sys.stdout = redirected_stdout
    try:
        ...something that does prints...
    finally:
        sys.stdout = save_stdout
    ...use redirected_stdout.value...
    redirectred_stdout.close()


Alex



More information about the Python-list mailing list