Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - printing to more than one output [duplicate]

Possible Duplicate:
How do I duplicate sys.stdout to a log file in python?

Is it possible for Python print command or other Python command to print a string to two destinations? For example, I would like to print both to the console and to output file in one statement (so that I don't need to duplicate print statements).

Preferably, I'd like to have a solution for Python 2.x if that may matter.

like image 431
Piotr Sobczyk Avatar asked Aug 21 '12 07:08

Piotr Sobczyk


2 Answers

Theoretically, you can 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 abandon print and just use logging, because that is essentially what you want.

like image 56
georg Avatar answered Nov 20 '22 21:11

georg


A comment to @carls's comment (I don't have reputation to comment yet):

From Python's documentation:

It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent try-finally blocks:

>>> with open('/tmp/workfile', 'r') as f:
...     read_data = f.read()
>>> f.closed
True
like image 22
Walton Avatar answered Nov 20 '22 22:11

Walton