direct print to log file

Benjamin Kaplan benjamin.kaplan at case.edu
Tue Oct 5 10:48:23 EDT 2010


On Tue, Oct 5, 2010 at 10:41 AM, Dave Angel <davea at ieee.org> wrote:

>  On 2:59 PM, Dirk Nachbar wrote:
>
>> How can I direct all print to a log file, eg some functions have their
>> own print and I cannot put a f.write() in front of it.
>>
>> Dirk
>>
>>
> When code does a print() without specifying a file, it goes to sys.stdout
>   So you just have to create a new file object and bind sys.stdout to it.
>
> (untested)
>
> import sys
>
> sys.stdout = open("mylogfile.txt", "w")
> or in your case   sys.stdout = f
>
> If you want to be able to go back to the original, then first bind another
> symbol to it.
> orig = sys.stdout
> sys.stdout = f
> ----do stuff----
> sys.stdout = orig
>
> DaveA
>

The original sys.stdout is stored as sys.__stdout__ so there's no need to
store it yourself.

>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20101005/93fbd79a/attachment.html>


More information about the Python-list mailing list