connect file object to standard output?

Scott David Daniels scott.daniels at acm.org
Mon May 8 16:24:21 EDT 2006


beliavsky at aol.com wrote:
> .... I think there is a way to connect standard output to a
> file, but I'd prefer not to do that, since I want to use plain print
> statements to warn about errors in the function and have their output
> appear on the screen. Thanks.
> 
> def write_data(data,out_file=""):
>     if (out_file != ""):
>         fp = open(out_file,"w")
>     else:
>         fp = # how to connect standard output to fp?
           fp = None
>     print >>fp, data
>     # more print>>fp statements follow


If you are only using "print >>x"-style statements, simply
set fp to None (which means "write on stdout").  That makes it
easier to only close the file you opened later., say by ending
the routine above with:

       if fp is not None:
           fp.close()

--Scott David Daniels
scott.daniels at acm.org



More information about the Python-list mailing list