How to send output to file

Stefan Schwarzer sschwarzer at sschwarzer.net
Fri Jan 24 00:14:10 CET 2003


Gerrit Holl wrote:
> A schreef op dinsdag 21 januari om 09:54:37 +0000:
>> I use httplib module.
>> By h.set_debuglevel(1) I start debugging but the output is written to DOS window.
>> How can  I divert the output to file instead.
>> Thank you for help.
> 
> You can assing to sys.stdout
> 
> import sys
> sys.stdout = open("myfile.log", "w")

Specifically, you can set and reset sys.stdout:

sys.stdout = open("myfile.log", "w")  # like above
try:
     # do things that write to sys.stdout
finally:
     # sys.__stdout__ contains the "real" standard output
     sys.stdout = sys.__stdout__

Note that the above approach will also affect print statements in other threads
than the one which should use the redirection.

Stefan





More information about the Python-list mailing list