Is it possible to somehow write to the file everything that is displayed in the console? I know about the existence of the logging module, but I have too much print to redo everything under logging
3 answers
I prefer the option of replacing sys.stdout with my own implementation, which will do everything that is needed. Here is the doped version with enSO :
import sys class Tee(object): def __init__(self, name, mode): self.file = open(name, mode) self.stdout = sys.stdout def __del__(self): self.close() def write(self, data): self.stdout.write(data) self.file.write(data) def flush(self): self.stdout.flush() self.file.flush() def close(self): if sys.stdout is self: sys.stdout = self.stdout self.file.close() sys.stdout = Tee('log.txt', 'a') And no replacements print on printer is necessary :)
- good decision - Igor Igoryach
- 2
s/знаком/хаком/- jfs
|
How about taking the path of least resistance and using standard tools in the face of the logging module?
If DEBUG annoying in the message, you need to remove the line %(levelname)-8s
And in order to continue to use print 'om, make a simple replacement (as correctly noted in the andreymal comment, when outputting with other arguments, and not just with the message itself, problems may arise):
import logging import sys def get_logger(name=__file__, file='log.txt', encoding='utf-8'): log = logging.getLogger(name) log.setLevel(logging.DEBUG) formatter = logging.Formatter('[%(asctime)s] %(filename)s:%(lineno)d %(levelname)-8s %(message)s') fh = logging.FileHandler(file, encoding=encoding) fh.setFormatter(formatter) log.addHandler(fh) sh = logging.StreamHandler(stream=sys.stdout) sh.setFormatter(formatter) log.addHandler(sh) return log log = get_logger() print = log.debug # Обходное решение надуманной проблемы несоответствия аргументов print и debug. # Приятным "побочным" эффектом будет возможность просто писать print() # print = lambda text="": log.debug(text) if __name__ == '__main__': log.debug('foo') log.debug('bar') print('') print('foo') print('bar') Console:
[2017-08-27 03:41:29,929] FOO_TEST_TEST.py:32 DEBUG foo [2017-08-27 03:41:29,929] FOO_TEST_TEST.py:33 DEBUG bar [2017-08-27 03:41:29,929] FOO_TEST_TEST.py:35 DEBUG [2017-08-27 03:41:29,929] FOO_TEST_TEST.py:36 DEBUG foo [2017-08-27 03:41:29,929] FOO_TEST_TEST.py:37 DEBUG bar printandlog.debugdifferent arguments, you can accidentally shoot a leg - andreymal- @andreymal, well, do not be so scary :) the most that happens is that something will not come out or if you try to deduce there will be an error, which is natural - not a natural way :) - gil9red
- And then they will run here with the question “why the print broke,” forgetting that the print was replaced somewhere at the beginning of the file :) - andreymal
- @andreymal according to this logic, people can generally recommend not to program, otherwise they will be mistaken. :) - Nick Volynkin ♦
|
Carried out by
def printer(printing): log_file = open("log.txt", "a") print(str(datetime.now())+ ' ' + str(printing)) log_file.write(str(datetime.now()) + ' ' + str(printing) + '\n') log_file.close() return printer And replaced all print to printer
- 2but it was possible not to replace, but simply to write:
print = printerand continue to use print :) - gil9red - 2@ gil9red: you can even not write printer:
from exterminate import AltPrint# $ pip install exterminate(note: the text is sent to gizoogle). - jfs - @jfs, judging by the examples of some wild library :) And judging by the code, the text is sent to gizoogle only to make a translation into the Daleks language - gil9red
- @ gil9red if it's not clear, my comment doesn’t have a smile;) - jfs
- @jfs, I agree, cool library :) - gil9red
|