5

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.

0

2 Answers 2

13

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Wouldn't you want to close the log file after writing to it?
it should close automatically in the destructor
@carl, actually, I think it should close when it goes out of scope - at the end of write...
I think @carl meant to the destructor of open('/tmp/log', 'a')
2

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.