connect file object to standard output?

Larry Bates larry.bates at
Mon May 8 17:28:46 CEST 2006

beliavsky at wrote:
> I want to write a function that writes to an output file if specified
> and otherwise to standard output. How can I connect a file object to
> standard output in the code below? I could use an if statement to
> choose between print and print>>fp throughout the function, but this
> seems awkward. 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?
>     print>>fp,data
>     # more print>>fp statements follow
import sys

def write_data(data, out_file=None):
    if out_file is None:
        fp = sys.stdout # how to connect standard output to fp?
        fp = open(out_file,"w")

    # more fp.write() statements follow

-Larry Bates

More information about the Python-list mailing list