There is a Python script:
import syssys.studout = open span> ( 'my_log.log' , 'w' ) print 'test' he writes the entire standard output to the file. Question: How can I write to the file and at the same time display to the console?
question@mail.ru
·
01.01.1970 03:00
There is a Python script:
import syssys.studout = open span> ( 'my_log.log' , 'w' ) print 'test' he writes the entire standard output to the file. Question: How can I write to the file and at the same time display to the console?
answer@mail.ru
·
01.01.1970 03:00
as an applied solution, literally performing the task voiced in the question: you can create a class that takes two file objects, and when writing in an object of this class, make an entry in both file objects.
from __future__ import print_function import sys class dublewrite : def __ init __ ( def write ( self, s ): self.file1.write self.file2.write (s) def flush ( self ): self.file1.flush () self.file2.flush () logfile = open ( 'my_log.log' , 'w' ) sys.studout = DOBLEWRITE (SYS.STDOUT, LOGFILE) print () logging
update.
for the correct redirecting and subsequent restoration of sys.Stdout in Python 3, it is better to use the context manager. In the standard Python 2 library, such a context manager, unfortunately, is not.
an example of use (for python 3):
import sys from contextlib import redirect_stdout class dublewrite : ... with open ( 'my_log.log' , 'w' ) as logfile: with redirect_stdout (dublewrite (sys.studut, logfile)): Print ( 'test' ) sys.stdout will be restored.