Can I write to terminal and a given file with one command in Python?
开发者_Python百科I have seen this question answered in reference to Bash, but can't find one for Python. Apologies if this is repeating something.
Is it possible to print to the terminal and an output file with one command? I'm familiar with using print >>
and sys.stdout = WritableObject
, but I'd like to avoid having to double print commands for each line I want logged.
I'm using Python 2.6, just in case such knowledge is necessary.
More importantly, I want this to run on a Windows-based system using IDLE's command line. So, in essence, I want the python script to report to IDLE's terminal and a given log file.
EDIT: For anyone who finds this and decides to go with the answer I chose, if you need help understanding context managers (like I did), I recommend Doug Hellman's Python Modules of the Week for clarification. This one details the context library. For help with decorators see this Stack Overflow question's answers.
Replace sys.stdout
.
class PrintAndLog(object):
def __init__(self, fileOrPath): # choose which makes more sense
self._file = ...
def write(s):
sys.stdout.write(s)
self._file.write(s)
def close(self):
self._file.close()
# insert wrappers for .flush, .writelines
_old_stdout = sys.stdout
sys.stdout = PrintAndLog(f)
... # print and stuff
sys.stdout = _old_stdout
Can be put into a context manager (this is at least the third time I see something like this on SO alone...):
from contextlib import contextmanager
@contextmanager
def replace_stdout(f):
old_stdout = sys.stdout
try:
sys.stdout = PrintAndLog(f)
yield
finally:
sys.stdout = old_stdout
Why not just write a function?
def myPrint(anOpenFileObject, message):
print message
anOpenFileObject.write(message)
If you're in Unix: At the start of your program, you could mkfifo a named pipe, and launch in the bg a cat from it to a tee of the terminal and the desired output file. Then throughout your program, output to the fd of the named pipe. Finally, rm the named pipe just before exiting.
But honestly I would just make a wrapper around print that prints to both dests.
精彩评论