Python - printing on multiple exits

Possible duplicate:
How to duplicate the sys.stdout file in a log file in python?

Is it possible for a Python command printor another Python command to print a string to two destinations? For example, I would like to print both on the console and output the file in one expression (so I do not need to duplicate operators print).

It is advisable that I have a solution for Python 2.x, if that can make a difference.

+5
source share
2 answers

Theoretically, you could try something like:

class Out(object):
    def write(self, s):
        sys.__stdout__.write(s)
        open('/tmp/log', 'a').write(s)

sys.stdout = Out()

...

print something # prints to stdout and logs

but a cleaner way would be to give up printand just use logging , because that is essentially what you want.

+13

@carls ( , ):

Python:

with . , , . , try-finally:

>>> with open('/tmp/workfile', 'r') as f:
...     read_data = f.read()
>>> f.closed
True
+2

All Articles