[Tutor] Redirecting output

Don Arnold Don Arnold" <darnold02@sprynet.com
Mon Jun 16 22:38:06 2003


----- Original Message -----
From: "Rick Owen" <rickowen@yahoo.com>
To: <tutor@python.org>
Sent: Monday, June 16, 2003 9:10 PM
Subject: [Tutor] Redirecting output


> Greetings,
>
> I have a script that scans log files for error messages.  Normally it just
> outputs the error messages to stdout with the print statement. I want to
add
> the option to specify an output file.  If an output file is specified then
I
> want to print to the output file otherwise I want to print to stdout.
>
> What I don't want to do (unless I have to) is
>
> if output:
>    print >> f, error_message
> else:
>    print error_message
>
> Is there a way to explicitly open sys.stdout so that it is assigned to f
if no
> output file is specified. That way I can always use
>
> print >> f, error_message
>
> where f would be either the output file or stdout.
>
> Thanks,
> Rick.
>

Actually it's simpler than that: you can just rebind sys.stdout and use
vanilla print for all your output:

import sys

oldout = sys.stdout
print 'redirecting'
sys.stdout = open('c:/temp2/stuff','w')
for i in range(10):
    print i
sys.stdout.close()
sys.stdout = oldout
print 'back to normal'

HTH,
Don