direct print to log file

D

Dirk Nachbar

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
 
D

Diez B. Roggisch

Dirk Nachbar said:
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.

you can replace sys.stdout with something that performs logging.

class MyWriter(object):

def __init__(self, old_stream):
self.old_stream = old_stream
self.logger = logging.getLogger("stdout")


def write(self, msg):
self.old_stream.write(msg)
self.logger.debug(msg)


sys.stdout = MyWriter(sys.stdout)

Untested - but you get the gist.

Diez
 
D

Dave Angel

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
 
S

Sion Arrowsmith

Dave Angel said:
If you want to be able to go back to the original, then first bind
another symbol to it.

Or restore from sys.__stdout__, as long as you're sure that nothing
else has rebound sys.stdout first (or don't mind clobbering it).
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,070
Latest member
BiogenixGummies

Latest Threads

Top