How do I redirect output to a file and to the console screen?

2

28tommy

Hi there,

I'm doing some TELNET and FTP sessions with my scripts. I need to
redirect all the output (and not just what I print) to an output file,
but still be able to see the session in process on the console.

The Console screen is of less importance, so I could give it up, but
what I'm looking for is a way to see all the interaction with the
remote seesions on a file, that all the console data was redirected to
it from within the script file.

P.S. - the command "python script_file > output_file" is not from
within the file, so it won't work for me.

Thank you (-:
 
M

Martin Miller

The basic way to redirect output is to reassign a value to sys.stdout
-- something along these lines:

# redirect stdout to a disk file
import sys
saveout = sys.stdout
outfile = open('output.txt', 'w')
sys.stdout = outfile

# output stuff
print 'hello world'

# restore stdout
outfile.flush()
outfile.close()
sys.stdout = saveout:

Essentially what you want is to have output redirected to *two*
different streams at the same time, the original stdout and a file.
Here's a link to a (very old) post on the subject that should help (see
'class Tee') if coupled with the above:

-Martin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,733
Messages
2,569,440
Members
44,830
Latest member
ZADIva7383

Latest Threads

Top