1

Newb python question. I've been reading up on tee() and different ways of splitting output. But i cant find a good example for splitting output to the terminal and to a log file. I've been playing around with some options and this is what I have so far:

def logname():
    env.warn_only = True
    timestamp = time.strftime("%d_%b_%Y")
    return "%s_%s" % (env.host_string, timestamp)

sys.stdout = open('/home/path/to/my/log/directory/%s' % logname(), 'w')

The above will log to a file with the host name_datestamp but won't display anything on screen. Then when I want to stop logging i do:

sys.stdout = sys.__stdout__ 

How can I log to my file with the definiton above and display to the terminal at the same time? Am I on the right path with tee()?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Kryten
  • 595
  • 3
  • 10
  • 25
  • 4
    `tee()` works for iterables (data *producers*) not for file streams (data *consumers*, really). Use the [`logging` module](http://docs.python.org/2/library/logging.html) to handle logging and configure that to log both to the filesystem and to the terminal. – Martijn Pieters May 14 '13 at 18:04
  • 1
    There are several good answers in the "possible duplicate" AaronD pointed out, including the answer I've just posted ;) – shx2 May 14 '13 at 19:56

1 Answers1

0

Like this?

[user@machine ~]$ python
Python 2.7.3 (default, Aug  9 2012, 17:23:57) 
[GCC 4.7.1 20120720 (Red Hat 4.7.1-5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> 
>>> class Tee(object):
...     def __init__(self, logfile, stdio = sys.__stdout__):
...         self.logf = open(logfile, 'w')
...         self.stdio = stdio
...     def write(self, data):
...         self.logf.write(data)
...         self.stdio.write(data)
...     def flush(self):
...         self.logf.flush()
...         self.stdio.flush()
...     def __getattr__(self, k):
...         return getattr(self.stdio, k)
...     def __dir__(self):
...         return dir(self.stdio)
... 
>>> sys.stdout = Tee('/tmp/output')
>>> print 'some test output'
some test output
>>> 
[user@machine ~]$ cat /tmp/output 
some test output
[user@machine ~]$ 
tMC
  • 18,105
  • 14
  • 62
  • 98