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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With