I have a program that performs calculations and shows them in the python console, reviewing a little documentation I have been able to store the results of the console to a txt file.
What I am looking for now is that every time I rerun the txt file is cleaned, so that the previous results of the console are not accumulated in the txt.
from loggerPrint import Logger
print_console = Logger('out_of_console.txt')
print('This is an example:')
print('Element',5*' ', 'Value')
values = [1,2,3,4,5,6,7,8,9,10]
for i in values:
print(i,11*' ', values[5])
print_console.close()
The class
import sys, os
class Logger(object):
"""
Lumberjack class - duplicates sys.stdout to a log file and it's okay
source: https://stackoverflow.com/a/24583265/5820024
"""
def __init__(self, filename="Prints_k", mode="ab", buff=0):
self.stdout = sys.stdout
self.file = open(filename, mode, buff)
sys.stdout = self
def __del__(self):
self.close()
def __enter__(self):
pass
def __exit__(self, *args):
pass
def write(self, message):
self.stdout.write(message)
self.file.write(message.encode("utf-8"))
def flush(self):
self.stdout.flush()
self.file.flush()
os.fsync(self.file.fileno())
def close(self):
if self.stdout != None:
sys.stdout = self.stdout
self.stdout = None
if self.file != None:
self.file.close()
self.file = None
While searching, I found the class 'Logger', in my case it works if in the write method the variable is defined like this: self.file.write (message.encode ("utf-8")), I leave a little more documentation in the following link: How to print the console to a text file AFTER the program finishes (Python)?
If someone has experience in handling classes and understands a little better, I would appreciate it, you could include a new method called clear, or do it in another way.
Best regards.